From f38d1d702e3d2a84b9f1cbb01ad9177e944a1847 Mon Sep 17 00:00:00 2001 From: Harsh Parikh Date: Fri, 27 Nov 2026 20:44:11 -0800 Subject: [PATCH 1/6] Delete grain/_src/python/ipc/shared_memory_array.py --- grain/_src/python/ipc/shared_memory_array.py | 243 ------------------- 1 file changed, 243 deletions(-) delete mode 100644 grain/_src/python/ipc/shared_memory_array.py diff --git a/grain/_src/python/ipc/shared_memory_array.py b/grain/_src/python/ipc/shared_memory_array.py deleted file mode 100644 index 3cef38e63..000000000 --- a/grain/_src/python/ipc/shared_memory_array.py +++ /dev/null @@ -1,243 +0,0 @@ -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -"""Shared memory array.""" - -from __future__ import annotations - -import dataclasses -import functools -import math -import mmap -from multiprocessing import pool -from multiprocessing import shared_memory -import threading -from typing import Any, Iterable - -from grain._src.core import tree_lib -import numpy as np -import numpy.typing as npt - - -@dataclasses.dataclass(slots=True, frozen=True) -class SharedMemoryArrayMetadata: - name: str - shape: Iterable[int] - dtype: npt.DTypeLike - - def close_and_unlink_shm(self) -> None: - """Closes and unlinks the shared memory referred to by this instance.""" - shm = shared_memory.SharedMemory(self.name) - shm.close() - shm.unlink() - - -def _del_shm(shm: shared_memory.SharedMemory, unlink: bool) -> None: - shm.close() - if unlink: - shm.unlink() - - -class SharedMemoryArray(np.ndarray): - """A NumPy array subclass which is backed by shared memory. - - This should be used in combination with Python multiprocessing. - Compared with the normal NumPy ndarray it avoids expensive serialization - when sending the array to another Python process (on the same machine). - It also doesn't require a copy on the receiving side. - - The last processes using the array must call unlink_on_del()! Otherwise - the memory will not be freed. - """ - - _lock: threading.Lock = threading.Lock() - _del_thread_pool: pool.ThreadPool | None = None - _outstanding_del_requests: threading.Semaphore | None = None - - def __new__( - cls, - shape: Iterable[int], - dtype: npt.DTypeLike = float, - ): - # See https://numpy.org/doc/stable/user/basics.subclassing.html - size = math.prod(shape) * np.dtype(dtype).itemsize - shm = shared_memory.SharedMemory(create=True, size=size) - return cls.from_shared_memory(shm, shape, dtype) - - def __array_finalize__(self, obj): - # This follows the `numpy.memmap` implementation - if hasattr(obj, "shm") and np.may_share_memory(self, obj): - self.shm = obj.shm - else: - self.shm = None - self._unlink_on_del = getattr(obj, "_unlink_on_del", False) - - def __getitem__(self, index: Any) -> Any: - # This follows the `numpy.memmap` implementation - res = super().__getitem__(index) - if isinstance(res, SharedMemoryArray) and res.shm is None: - return res.view(np.ndarray) - return res - - def __array_wrap__(self, obj, context=None, return_scalar=False): # pylint: disable=unused-argument - # This follows the `numpy.memmap` implementation - if self is obj or type(self) is not type(self): - return obj - if return_scalar: - return obj[()] - return obj.view(np.ndarray) - - @classmethod - def from_metadata( - cls, metadata: SharedMemoryArrayMetadata - ) -> SharedMemoryArray: - shm = shared_memory.SharedMemory(metadata.name) - return cls.from_shared_memory(shm, metadata.shape, metadata.dtype) - - @property - def metadata(self) -> SharedMemoryArrayMetadata: - shm = self.shm - assert isinstance(shm, shared_memory.SharedMemory) - return SharedMemoryArrayMetadata( - name=shm.name, shape=self.shape, dtype=self.dtype - ) - - @classmethod - def from_shared_memory( - cls, - shm: shared_memory.SharedMemory, - shape: Any, - dtype: npt.DTypeLike, - ) -> SharedMemoryArray: - obj = super().__new__(cls, shape, dtype, buffer=shm.buf) - obj.shm = shm - obj._unlink_on_del = False - return obj - - def __reduce_ex__(self, protocol): - # For out-of-band pickling we don't need a PickleBuffer because the - # `SharedMemory` class automatically pickles itself using only its name - return self.from_shared_memory, (self.shm, self.shape, self.dtype) - - @classmethod - def enable_async_del( - cls, num_threads: int = 1, max_outstanding_requests: int = 50 - ) -> None: - """Enables asynchronous deletion of shared memory arrays. - - Args: - num_threads: The number of threads to use for deletion. - max_outstanding_requests: The maximum number of outstanding requests to - close/unlink shared memory. A larger value may make the __del__ method - 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. - """ - 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 - ) - - # For use in tests. - @classmethod - def _disable_async_del(cls) -> None: - cls._del_thread_pool = None - cls._outstanding_del_requests = None - - # Mocked in tests, so be careful refactoring. - @classmethod - def close_shm_async( - cls, - shm: shared_memory.SharedMemory, - unlink: bool, - ) -> None: - try: - _del_shm(shm, unlink) - finally: - assert cls._outstanding_del_requests is not None - cls._outstanding_del_requests.release() - - def unlink_on_del(self) -> None: - """Mark this object responsible for unlinking the shared memory.""" - self._unlink_on_del = True - - def __del__(self) -> None: - # Ensure that this array is not a view before closing shared memory - if not isinstance(self.base, mmap.mmap): - return - thread_pool = SharedMemoryArray._del_thread_pool - outstanding_del_requests = SharedMemoryArray._outstanding_del_requests - shm = self.shm - assert isinstance(shm, shared_memory.SharedMemory) - if thread_pool: - assert outstanding_del_requests is not None - # We use a semaphore to make sure that we don't accumulate too many - # requests to close/unlink shared memory, which could lead to OOM errors. - if outstanding_del_requests.acquire(blocking=False): - thread_pool.apply_async( - SharedMemoryArray.close_shm_async, args=(shm, self._unlink_on_del) - ) - else: - _del_shm(shm, unlink=self._unlink_on_del) - else: - _del_shm(shm, unlink=self._unlink_on_del) - - -def _copy_leaf_to_shm(leaf: Any, min_size: int = 0) -> Any: - """Copies `leaf` to shared memory if it's a big enough numpy array.""" - if isinstance(leaf, SharedMemoryArray): - return leaf.metadata - if ( - not isinstance(leaf, np.ndarray) - or leaf.dtype.hasobject - or not leaf.flags.c_contiguous - or math.prod(leaf.shape) == 0 - or leaf.nbytes < min_size - ): - return leaf - - shared_memory_arr = SharedMemoryArray(leaf.shape, leaf.dtype) - np.copyto(shared_memory_arr, leaf, casting="no") - return shared_memory_arr.metadata - - -def copy_to_shm(struct: Any, min_size: int = 0) -> Any: - """Copies leaf ndarrays of the structure to shared memory.""" - return tree_lib.map_structure( - functools.partial(_copy_leaf_to_shm, min_size=min_size), struct - ) - - -def _open_leaf_from_shm(leaf: Any) -> Any: - """Recovers `leaf` from shared memory if it's a numpy array metadata.""" - if isinstance(leaf, SharedMemoryArrayMetadata): - leaf = SharedMemoryArray.from_metadata(leaf) - leaf.unlink_on_del() - return leaf - - -def open_from_shm(struct: Any) -> Any: - """Recovers leaf ndarrays of the structure from shared memory.""" - return tree_lib.map_structure(_open_leaf_from_shm, struct) - - -def _unlink_shm_if_metadata(obj: Any) -> None: - if isinstance(obj, SharedMemoryArrayMetadata): - obj.close_and_unlink_shm() - - -def unlink_shm(struct: Any) -> None: - tree_lib.map_structure(_unlink_shm_if_metadata, struct) From f74e24ce37020556554e3e6aa12a79f172faf0b2 Mon Sep 17 00:00:00 2001 From: Harsh Parikh Date: Fri, 27 Nov 2026 20:44:47 -0800 Subject: [PATCH 2/6] Record the async deletion settings in SharedMemoryArray --- grain/_src/python/ipc/shared_memory_array.py | 287 +++++++++++++++++++ 1 file changed, 287 insertions(+) create mode 100644 grain/_src/python/ipc/shared_memory_array.py diff --git a/grain/_src/python/ipc/shared_memory_array.py b/grain/_src/python/ipc/shared_memory_array.py new file mode 100644 index 000000000..ca60be3b8 --- /dev/null +++ b/grain/_src/python/ipc/shared_memory_array.py @@ -0,0 +1,287 @@ +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Shared memory array.""" + +from __future__ import annotations + +import dataclasses +import functools +import math +import mmap +from multiprocessing import pool +from multiprocessing import shared_memory +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 + + +@dataclasses.dataclass(slots=True, frozen=True) +class SharedMemoryArrayMetadata: + name: str + shape: Iterable[int] + dtype: npt.DTypeLike + + def close_and_unlink_shm(self) -> None: + """Closes and unlinks the shared memory referred to by this instance.""" + shm = shared_memory.SharedMemory(self.name) + shm.close() + 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: + shm.unlink() + + +class SharedMemoryArray(np.ndarray): + """A NumPy array subclass which is backed by shared memory. + + This should be used in combination with Python multiprocessing. + Compared with the normal NumPy ndarray it avoids expensive serialization + when sending the array to another Python process (on the same machine). + It also doesn't require a copy on the receiving side. + + The last processes using the array must call unlink_on_del()! Otherwise + the memory will not be freed. + """ + + _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, + shape: Iterable[int], + dtype: npt.DTypeLike = float, + ): + # See https://numpy.org/doc/stable/user/basics.subclassing.html + size = math.prod(shape) * np.dtype(dtype).itemsize + shm = shared_memory.SharedMemory(create=True, size=size) + return cls.from_shared_memory(shm, shape, dtype) + + def __array_finalize__(self, obj): + # This follows the `numpy.memmap` implementation + if hasattr(obj, "shm") and np.may_share_memory(self, obj): + self.shm = obj.shm + else: + self.shm = None + self._unlink_on_del = getattr(obj, "_unlink_on_del", False) + + def __getitem__(self, index: Any) -> Any: + # This follows the `numpy.memmap` implementation + res = super().__getitem__(index) + if isinstance(res, SharedMemoryArray) and res.shm is None: + return res.view(np.ndarray) + return res + + def __array_wrap__(self, obj, context=None, return_scalar=False): # pylint: disable=unused-argument + # This follows the `numpy.memmap` implementation + if self is obj or type(self) is not type(self): + return obj + if return_scalar: + return obj[()] + return obj.view(np.ndarray) + + @classmethod + def from_metadata( + cls, metadata: SharedMemoryArrayMetadata + ) -> SharedMemoryArray: + shm = shared_memory.SharedMemory(metadata.name) + return cls.from_shared_memory(shm, metadata.shape, metadata.dtype) + + @property + def metadata(self) -> SharedMemoryArrayMetadata: + shm = self.shm + assert isinstance(shm, shared_memory.SharedMemory) + return SharedMemoryArrayMetadata( + name=shm.name, shape=self.shape, dtype=self.dtype + ) + + @classmethod + def from_shared_memory( + cls, + shm: shared_memory.SharedMemory, + shape: Any, + dtype: npt.DTypeLike, + ) -> SharedMemoryArray: + obj = super().__new__(cls, shape, dtype, buffer=shm.buf) + obj.shm = shm + obj._unlink_on_del = False + return obj + + def __reduce_ex__(self, protocol): + # For out-of-band pickling we don't need a PickleBuffer because the + # `SharedMemory` class automatically pickles itself using only its name + return self.from_shared_memory, (self.shm, self.shape, self.dtype) + + @classmethod + def enable_async_del( + cls, num_threads: int = 1, max_outstanding_requests: int = 50 + ) -> None: + """Enables asynchronous deletion of shared memory arrays. + + Args: + num_threads: The number of threads to use for deletion. + max_outstanding_requests: The maximum number of outstanding requests to + close/unlink shared memory. A larger value may make the __del__ method + 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 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 + def close_shm_async( + cls, + shm: shared_memory.SharedMemory, + unlink: bool, + ) -> None: + try: + _del_shm(shm, unlink) + finally: + assert cls._outstanding_del_requests is not None + cls._outstanding_del_requests.release() + + def unlink_on_del(self) -> None: + """Mark this object responsible for unlinking the shared memory.""" + self._unlink_on_del = True + + def __del__(self) -> None: + # Ensure that this array is not a view before closing shared memory + if not isinstance(self.base, mmap.mmap): + return + thread_pool = SharedMemoryArray._del_thread_pool + outstanding_del_requests = SharedMemoryArray._outstanding_del_requests + shm = self.shm + assert isinstance(shm, shared_memory.SharedMemory) + if thread_pool: + assert outstanding_del_requests is not None + # We use a semaphore to make sure that we don't accumulate too many + # requests to close/unlink shared memory, which could lead to OOM errors. + if outstanding_del_requests.acquire(blocking=False): + thread_pool.apply_async( + SharedMemoryArray.close_shm_async, args=(shm, self._unlink_on_del) + ) + else: + _del_shm(shm, unlink=self._unlink_on_del) + else: + _del_shm(shm, unlink=self._unlink_on_del) + + +def _copy_leaf_to_shm(leaf: Any, min_size: int = 0) -> Any: + """Copies `leaf` to shared memory if it's a big enough numpy array.""" + if isinstance(leaf, SharedMemoryArray): + return leaf.metadata + if ( + not isinstance(leaf, np.ndarray) + or leaf.dtype.hasobject + or not leaf.flags.c_contiguous + or math.prod(leaf.shape) == 0 + or leaf.nbytes < min_size + ): + return leaf + + shared_memory_arr = SharedMemoryArray(leaf.shape, leaf.dtype) + np.copyto(shared_memory_arr, leaf, casting="no") + return shared_memory_arr.metadata + + +def copy_to_shm(struct: Any, min_size: int = 0) -> Any: + """Copies leaf ndarrays of the structure to shared memory.""" + return tree_lib.map_structure( + functools.partial(_copy_leaf_to_shm, min_size=min_size), struct + ) + + +def _open_leaf_from_shm(leaf: Any) -> Any: + """Recovers `leaf` from shared memory if it's a numpy array metadata.""" + if isinstance(leaf, SharedMemoryArrayMetadata): + leaf = SharedMemoryArray.from_metadata(leaf) + leaf.unlink_on_del() + return leaf + + +def open_from_shm(struct: Any) -> Any: + """Recovers leaf ndarrays of the structure from shared memory.""" + return tree_lib.map_structure(_open_leaf_from_shm, struct) + + +def _unlink_shm_if_metadata(obj: Any) -> None: + if isinstance(obj, SharedMemoryArrayMetadata): + obj.close_and_unlink_shm() + + +def unlink_shm(struct: Any) -> None: + tree_lib.map_structure(_unlink_shm_if_metadata, struct) From d7de8bd5a6a472ab529d37e22a82d5afa02f8a91 Mon Sep 17 00:00:00 2001 From: Harsh Parikh Date: Fri, 27 Nov 2026 20:45:26 -0800 Subject: [PATCH 3/6] Delete grain/multiprocessing.py --- grain/multiprocessing.py | 25 ------------------------- 1 file changed, 25 deletions(-) delete mode 100644 grain/multiprocessing.py diff --git a/grain/multiprocessing.py b/grain/multiprocessing.py deleted file mode 100644 index 6c95ba8b0..000000000 --- a/grain/multiprocessing.py +++ /dev/null @@ -1,25 +0,0 @@ -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -"""APIs to work with multiprocessing.""" - - -# pylint: disable=g-importing-member -# pylint: disable=g-multiple-import -# pylint: disable=unused-import - -from grain._src.python.ipc.shared_memory_array import ( - SharedMemoryArray, - SharedMemoryArrayMetadata, -) -from grain._src.python.options import MultiprocessingOptions From 06e028c72e9a8be2e5229ba5a751ccf0118d3526 Mon Sep 17 00:00:00 2001 From: Harsh Parikh Date: Fri, 27 Nov 2026 20:45:49 -0800 Subject: [PATCH 4/6] Export AsyncDelSettings from grain.multiprocessing --- grain/multiprocessing.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 grain/multiprocessing.py diff --git a/grain/multiprocessing.py b/grain/multiprocessing.py new file mode 100644 index 000000000..17882c281 --- /dev/null +++ b/grain/multiprocessing.py @@ -0,0 +1,26 @@ +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""APIs to work with multiprocessing.""" + + +# pylint: disable=g-importing-member +# pylint: disable=g-multiple-import +# pylint: disable=unused-import + +from grain._src.python.ipc.shared_memory_array import ( + AsyncDelSettings, + SharedMemoryArray, + SharedMemoryArrayMetadata, +) +from grain._src.python.options import MultiprocessingOptions From 26470d3f95e5a5ce36d6648d53416390b21d8705 Mon Sep 17 00:00:00 2001 From: Harsh Parikh Date: Fri, 27 Nov 2026 20:46:29 -0800 Subject: [PATCH 5/6] Delete grain/_src/python/ipc/shared_memory_array_test.py --- .../python/ipc/shared_memory_array_test.py | 284 ------------------ 1 file changed, 284 deletions(-) delete mode 100644 grain/_src/python/ipc/shared_memory_array_test.py diff --git a/grain/_src/python/ipc/shared_memory_array_test.py b/grain/_src/python/ipc/shared_memory_array_test.py deleted file mode 100644 index f2e770095..000000000 --- a/grain/_src/python/ipc/shared_memory_array_test.py +++ /dev/null @@ -1,284 +0,0 @@ -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -"""Tests for shared memory array.""" - -from multiprocessing import shared_memory -import platform -import threading -import time -from unittest import mock - -from absl.testing import absltest -from absl.testing import parameterized -import multiprocessing -from grain._src.python import operations -from grain._src.python import record -from grain._src.python.ipc import shared_memory_array -import jax -import numpy as np - -SharedMemoryArray = shared_memory_array.SharedMemoryArray -SharedMemoryArrayMetadata = shared_memory_array.SharedMemoryArrayMetadata -copy_to_shm = shared_memory_array.copy_to_shm -open_from_shm = shared_memory_array.open_from_shm -unlink_shm = shared_memory_array.unlink_shm -BatchOperation = operations.BatchOperation - - -def _create_and_delete_shm() -> SharedMemoryArrayMetadata: - data = np.array([[1, 2], [3, 4]], dtype=np.int32) - shm_array = SharedMemoryArray(data.shape, data.dtype) - shm_array.unlink_on_del() - metadata = shm_array.metadata - return metadata - - -def _wait_for_deletion(metadata: SharedMemoryArrayMetadata) -> None: - while True: - try: - _ = shared_memory.SharedMemory(name=metadata.name, create=False) - time.sleep(0.1) - except FileNotFoundError: - break - - -@absltest.skipIf(platform.system() == "Windows", "Timeouts on Windows.") -class SharedMemoryArrayTest(parameterized.TestCase): - - @parameterized.parameters([ - "numpy", - "jax", - ]) - def test_batch_dict_of_data_with_shared_memory(self, mode): - data = [[1, 2], [3, 4]] - if mode == "numpy": - data = list(map(lambda x: np.array(x, dtype=np.int32), data)) - else: - data = list(map(jax.numpy.array, data)) - - input_data = iter([ - record.Record( - record.RecordMetadata(index=idx, record_key=idx + 1), - {"a": item}, - ) - for idx, item in enumerate(data) - ]) - - batch_operation = BatchOperation(batch_size=2) - batch_operation._enable_shared_memory() - expected_output_data = [ - record.Record( - record.RecordMetadata(index=1, record_key=None), - {"a": SharedMemoryArray((2, 2), np.int32)}, - ) - ] - expected_record = expected_output_data[0] - actual_output_data = list(batch_operation(input_data)) - self.assertLen(actual_output_data, len(expected_output_data)) - actual_record = actual_output_data[0] - # SharedMemory name is determined by OS and not known in advance. Thus - # checking for values of individual fields. - self.assertEqual(actual_record.metadata, expected_record.metadata) - self.assertIsInstance(actual_record.data, dict) - self.assertEqual(actual_record.data.keys(), {"a"}) - shm_metadata = actual_record.data["a"] - self.assertIsInstance(shm_metadata, SharedMemoryArrayMetadata) - self.assertEqual(shm_metadata.shape, (2, 2)) - self.assertEqual(shm_metadata.dtype, np.int32) - # Clean up the allocated shared memory block and make sure it no longer - # exists. - shm_metadata.close_and_unlink_shm() - with self.assertRaises(FileNotFoundError): - _ = shared_memory.SharedMemory(name=shm_metadata.name, create=False) - - def test_async_unlink_limit(self): - SharedMemoryArray._disable_async_del() - SharedMemoryArray.enable_async_del(max_outstanding_requests=1) - event = threading.Event() - original_close_shm_async = SharedMemoryArray.close_shm_async - - def _wait_for_event(shm, unlink_on_del): - event.wait(timeout=60) - original_close_shm_async(shm, unlink_on_del) - - with mock.patch.object( - SharedMemoryArray, "close_shm_async", side_effect=_wait_for_event - ): - metadata = _create_and_delete_shm() - time.sleep(1) - # This should succeed, since the unlink request is async and we haven't - # yet allowed it to progress past the event. - _ = shared_memory.SharedMemory(name=metadata.name, create=False) - - # All outstanding requests in use, so this should delete the shared memory - # right away. - metadata_2 = _create_and_delete_shm() - with self.assertRaises(FileNotFoundError): - _ = shared_memory.SharedMemory(name=metadata_2.name, create=False) - - event.set() - _wait_for_deletion(metadata) - - def test_del_no_pool(self): - SharedMemoryArray._disable_async_del() - # Tests deletion of SharedMemory resource when enable_async_del is not - # called. - data = np.array([[1, 2], [3, 4]], dtype=np.int32) - shm_array = SharedMemoryArray(data.shape, data.dtype) - shm_array.unlink_on_del() - metadata = shm_array.metadata - del shm_array - with self.assertRaises(FileNotFoundError): - _ = shared_memory.SharedMemory(name=metadata.name, create=False) - - def test_del_many_async(self): - SharedMemoryArray._disable_async_del() - SharedMemoryArray.enable_async_del( - num_threads=4, max_outstanding_requests=20 - ) - shm_metadatas = [_create_and_delete_shm() for _ in range(50)] - for metadata in shm_metadatas: - _wait_for_deletion(metadata) - - def test_del_many_async_reuse_pool(self): - max_outstanding_requests = 20 - SharedMemoryArray._disable_async_del() - SharedMemoryArray.enable_async_del( - num_threads=4, max_outstanding_requests=max_outstanding_requests - ) - original_close_shm_async = SharedMemoryArray.close_shm_async - - def my_close_shm_async(shm, unlink_on_del): - original_close_shm_async(shm, unlink_on_del) - - with mock.patch.object( - SharedMemoryArray, "close_shm_async", side_effect=my_close_shm_async - ) as mock_close_shm_async: - with self.subTest("first_round_of_requests"): - shm_metadatas = [ - _create_and_delete_shm() for _ in range(max_outstanding_requests) - ] - for metadata in shm_metadatas: - _wait_for_deletion(metadata) - self.assertEqual( - max_outstanding_requests, mock_close_shm_async.call_count - ) - with self.subTest("second_round_of_requests"): - # Do it again to make sure the pool is reused. - shm_metadatas = [ - _create_and_delete_shm() for _ in range(max_outstanding_requests) - ] - for metadata in shm_metadatas: - _wait_for_deletion(metadata) - self.assertEqual( - 2 * max_outstanding_requests, mock_close_shm_async.call_count - ) - - def test_failed_async_del_releases_its_slot(self): - SharedMemoryArray._disable_async_del() - SharedMemoryArray.enable_async_del(max_outstanding_requests=1) - self.addCleanup(SharedMemoryArray._disable_async_del) - outstanding_del_requests = SharedMemoryArray._outstanding_del_requests - assert outstanding_del_requests is not None - # `__del__` takes a slot before it schedules the deletion. - self.assertTrue(outstanding_del_requests.acquire(blocking=False)) - shm = mock.create_autospec(shared_memory.SharedMemory, instance=True) - - with mock.patch.object( - shared_memory_array, "_del_shm", side_effect=RuntimeError("del failed") - ): - with self.assertRaisesRegex(RuntimeError, "del failed"): - SharedMemoryArray.close_shm_async(shm, unlink=True) - - self.assertTrue(outstanding_del_requests.acquire(blocking=False)) - - def test_copy_and_open_shm_single_array(self): - arr = np.arange(10).astype(np.int32) - shm_struct = copy_to_shm(arr) - self.assertIsInstance(shm_struct, SharedMemoryArrayMetadata) - opened_struct = open_from_shm(shm_struct) - self.assertIsInstance(opened_struct, SharedMemoryArray) - np.testing.assert_array_equal(opened_struct, arr) - self.assertTrue(opened_struct._unlink_on_del) - - def test_copy_and_open_shm_nested_structure(self): - arr = np.arange(10).astype(np.int32) - arr2 = np.arange(5).astype(np.int32) - struct = {"a": arr, "b": [arr2, arr], "c": 123} - shm_struct = copy_to_shm(struct) - self.assertIsInstance(shm_struct["a"], SharedMemoryArrayMetadata) - self.assertIsInstance(shm_struct["b"][0], SharedMemoryArrayMetadata) - self.assertIsInstance(shm_struct["b"][1], SharedMemoryArrayMetadata) - self.assertEqual(shm_struct["c"], 123) - - opened_struct = open_from_shm(shm_struct) - self.assertIsInstance(opened_struct["a"], SharedMemoryArray) - np.testing.assert_array_equal(opened_struct["a"], arr) - self.assertTrue(opened_struct["a"]._unlink_on_del) - self.assertIsInstance(opened_struct["b"][0], SharedMemoryArray) - np.testing.assert_array_equal(opened_struct["b"][0], arr2) - self.assertTrue(opened_struct["b"][0]._unlink_on_del) - self.assertIsInstance(opened_struct["b"][1], SharedMemoryArray) - np.testing.assert_array_equal(opened_struct["b"][1], arr) - self.assertTrue(opened_struct["b"][1]._unlink_on_del) - self.assertEqual(opened_struct["c"], 123) - - def test_copy_and_open_shm_min_size(self): - arr = np.arange(10).astype(np.int32) # 40 bytes - shm_struct = copy_to_shm(arr, min_size=100) - self.assertIsInstance(shm_struct, np.ndarray) - np.testing.assert_array_equal(shm_struct, arr) - shm_struct = copy_to_shm(arr, min_size=10) - self.assertIsInstance(shm_struct, SharedMemoryArrayMetadata) - opened_struct = open_from_shm(shm_struct) - self.assertIsInstance(opened_struct, SharedMemoryArray) - np.testing.assert_array_equal(opened_struct, arr) - self.assertTrue(opened_struct._unlink_on_del) - - def test_unlink_shm(self): - arr = np.arange(10).astype(np.int32) - arr2 = np.arange(5).astype(np.int32) - struct = {"a": arr, "b": [arr2, arr], "c": 123} - shm_struct = copy_to_shm(struct) - names = [ - shm_struct["a"].name, - shm_struct["b"][0].name, - shm_struct["b"][1].name, - ] - # Check that SHMs exist. - for name in names: - self.assertIsNotNone(shared_memory.SharedMemory(name=name, create=False)) - - unlink_shm(shm_struct) - - for name in names: - with self.assertRaises(FileNotFoundError): - shared_memory.SharedMemory(name=name, create=False) - - def test_advanced_indexing_returns_numpy_array(self): - shm_arr = SharedMemoryArray((10, 2), np.int32) - shm_arr.unlink_on_del() - # Slicing returns a view backed by shared memory: - sliced = shm_arr[0:2] - self.assertIsInstance(sliced, SharedMemoryArray) - self.assertIsNotNone(sliced.shm) - - # Advanced indexing returns a regular NumPy array: - advanced = shm_arr[[0, 2]] - self.assertNotIsInstance(advanced, SharedMemoryArray) - self.assertIsInstance(advanced, np.ndarray) - - -if __name__ == "__main__": - absltest.main() From f89ef38105bf3a8bcfabd8d22a543dc80bba55d7 Mon Sep 17 00:00:00 2001 From: Harsh Parikh Date: Fri, 27 Nov 2026 20:47:05 -0800 Subject: [PATCH 6/6] Add tests for the async deletion settings --- .../python/ipc/shared_memory_array_test.py | 362 ++++++++++++++++++ 1 file changed, 362 insertions(+) create mode 100644 grain/_src/python/ipc/shared_memory_array_test.py diff --git a/grain/_src/python/ipc/shared_memory_array_test.py b/grain/_src/python/ipc/shared_memory_array_test.py new file mode 100644 index 000000000..595ef0d41 --- /dev/null +++ b/grain/_src/python/ipc/shared_memory_array_test.py @@ -0,0 +1,362 @@ +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Tests for shared memory array.""" + +from multiprocessing import shared_memory +import platform +import threading +import time +from unittest import mock + +from absl.testing import absltest +from absl.testing import parameterized +import multiprocessing +from grain._src.python import operations +from grain._src.python import record +from grain._src.python.ipc import shared_memory_array +import jax +import numpy as np + +SharedMemoryArray = shared_memory_array.SharedMemoryArray +SharedMemoryArrayMetadata = shared_memory_array.SharedMemoryArrayMetadata +copy_to_shm = shared_memory_array.copy_to_shm +open_from_shm = shared_memory_array.open_from_shm +unlink_shm = shared_memory_array.unlink_shm +BatchOperation = operations.BatchOperation + + +def _create_and_delete_shm() -> SharedMemoryArrayMetadata: + data = np.array([[1, 2], [3, 4]], dtype=np.int32) + shm_array = SharedMemoryArray(data.shape, data.dtype) + shm_array.unlink_on_del() + metadata = shm_array.metadata + return metadata + + +def _wait_for_deletion(metadata: SharedMemoryArrayMetadata) -> None: + while True: + try: + _ = shared_memory.SharedMemory(name=metadata.name, create=False) + time.sleep(0.1) + except FileNotFoundError: + break + + +@absltest.skipIf(platform.system() == "Windows", "Timeouts on Windows.") +class SharedMemoryArrayTest(parameterized.TestCase): + + @parameterized.parameters([ + "numpy", + "jax", + ]) + def test_batch_dict_of_data_with_shared_memory(self, mode): + data = [[1, 2], [3, 4]] + if mode == "numpy": + data = list(map(lambda x: np.array(x, dtype=np.int32), data)) + else: + data = list(map(jax.numpy.array, data)) + + input_data = iter([ + record.Record( + record.RecordMetadata(index=idx, record_key=idx + 1), + {"a": item}, + ) + for idx, item in enumerate(data) + ]) + + batch_operation = BatchOperation(batch_size=2) + batch_operation._enable_shared_memory() + expected_output_data = [ + record.Record( + record.RecordMetadata(index=1, record_key=None), + {"a": SharedMemoryArray((2, 2), np.int32)}, + ) + ] + expected_record = expected_output_data[0] + actual_output_data = list(batch_operation(input_data)) + self.assertLen(actual_output_data, len(expected_output_data)) + actual_record = actual_output_data[0] + # SharedMemory name is determined by OS and not known in advance. Thus + # checking for values of individual fields. + self.assertEqual(actual_record.metadata, expected_record.metadata) + self.assertIsInstance(actual_record.data, dict) + self.assertEqual(actual_record.data.keys(), {"a"}) + shm_metadata = actual_record.data["a"] + self.assertIsInstance(shm_metadata, SharedMemoryArrayMetadata) + self.assertEqual(shm_metadata.shape, (2, 2)) + self.assertEqual(shm_metadata.dtype, np.int32) + # Clean up the allocated shared memory block and make sure it no longer + # exists. + shm_metadata.close_and_unlink_shm() + with self.assertRaises(FileNotFoundError): + _ = shared_memory.SharedMemory(name=shm_metadata.name, create=False) + + def test_async_unlink_limit(self): + SharedMemoryArray._disable_async_del() + SharedMemoryArray.enable_async_del(max_outstanding_requests=1) + event = threading.Event() + original_close_shm_async = SharedMemoryArray.close_shm_async + + def _wait_for_event(shm, unlink_on_del): + event.wait(timeout=60) + original_close_shm_async(shm, unlink_on_del) + + with mock.patch.object( + SharedMemoryArray, "close_shm_async", side_effect=_wait_for_event + ): + metadata = _create_and_delete_shm() + time.sleep(1) + # This should succeed, since the unlink request is async and we haven't + # yet allowed it to progress past the event. + _ = shared_memory.SharedMemory(name=metadata.name, create=False) + + # All outstanding requests in use, so this should delete the shared memory + # right away. + metadata_2 = _create_and_delete_shm() + with self.assertRaises(FileNotFoundError): + _ = shared_memory.SharedMemory(name=metadata_2.name, create=False) + + event.set() + _wait_for_deletion(metadata) + + def test_del_no_pool(self): + SharedMemoryArray._disable_async_del() + # Tests deletion of SharedMemory resource when enable_async_del is not + # called. + data = np.array([[1, 2], [3, 4]], dtype=np.int32) + shm_array = SharedMemoryArray(data.shape, data.dtype) + shm_array.unlink_on_del() + metadata = shm_array.metadata + del shm_array + with self.assertRaises(FileNotFoundError): + _ = shared_memory.SharedMemory(name=metadata.name, create=False) + + def test_del_many_async(self): + SharedMemoryArray._disable_async_del() + SharedMemoryArray.enable_async_del( + num_threads=4, max_outstanding_requests=20 + ) + shm_metadatas = [_create_and_delete_shm() for _ in range(50)] + for metadata in shm_metadatas: + _wait_for_deletion(metadata) + + def test_del_many_async_reuse_pool(self): + max_outstanding_requests = 20 + SharedMemoryArray._disable_async_del() + SharedMemoryArray.enable_async_del( + num_threads=4, max_outstanding_requests=max_outstanding_requests + ) + original_close_shm_async = SharedMemoryArray.close_shm_async + + def my_close_shm_async(shm, unlink_on_del): + original_close_shm_async(shm, unlink_on_del) + + with mock.patch.object( + SharedMemoryArray, "close_shm_async", side_effect=my_close_shm_async + ) as mock_close_shm_async: + with self.subTest("first_round_of_requests"): + shm_metadatas = [ + _create_and_delete_shm() for _ in range(max_outstanding_requests) + ] + for metadata in shm_metadatas: + _wait_for_deletion(metadata) + self.assertEqual( + max_outstanding_requests, mock_close_shm_async.call_count + ) + with self.subTest("second_round_of_requests"): + # Do it again to make sure the pool is reused. + shm_metadatas = [ + _create_and_delete_shm() for _ in range(max_outstanding_requests) + ] + for metadata in shm_metadatas: + _wait_for_deletion(metadata) + self.assertEqual( + 2 * max_outstanding_requests, mock_close_shm_async.call_count + ) + + def test_failed_async_del_releases_its_slot(self): + SharedMemoryArray._disable_async_del() + SharedMemoryArray.enable_async_del(max_outstanding_requests=1) + self.addCleanup(SharedMemoryArray._disable_async_del) + outstanding_del_requests = SharedMemoryArray._outstanding_del_requests + assert outstanding_del_requests is not None + # `__del__` takes a slot before it schedules the deletion. + self.assertTrue(outstanding_del_requests.acquire(blocking=False)) + shm = mock.create_autospec(shared_memory.SharedMemory, instance=True) + + with mock.patch.object( + shared_memory_array, "_del_shm", side_effect=RuntimeError("del failed") + ): + with self.assertRaisesRegex(RuntimeError, "del failed"): + SharedMemoryArray.close_shm_async(shm, unlink=True) + + 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) + self.assertIsInstance(shm_struct, SharedMemoryArrayMetadata) + opened_struct = open_from_shm(shm_struct) + self.assertIsInstance(opened_struct, SharedMemoryArray) + np.testing.assert_array_equal(opened_struct, arr) + self.assertTrue(opened_struct._unlink_on_del) + + def test_copy_and_open_shm_nested_structure(self): + arr = np.arange(10).astype(np.int32) + arr2 = np.arange(5).astype(np.int32) + struct = {"a": arr, "b": [arr2, arr], "c": 123} + shm_struct = copy_to_shm(struct) + self.assertIsInstance(shm_struct["a"], SharedMemoryArrayMetadata) + self.assertIsInstance(shm_struct["b"][0], SharedMemoryArrayMetadata) + self.assertIsInstance(shm_struct["b"][1], SharedMemoryArrayMetadata) + self.assertEqual(shm_struct["c"], 123) + + opened_struct = open_from_shm(shm_struct) + self.assertIsInstance(opened_struct["a"], SharedMemoryArray) + np.testing.assert_array_equal(opened_struct["a"], arr) + self.assertTrue(opened_struct["a"]._unlink_on_del) + self.assertIsInstance(opened_struct["b"][0], SharedMemoryArray) + np.testing.assert_array_equal(opened_struct["b"][0], arr2) + self.assertTrue(opened_struct["b"][0]._unlink_on_del) + self.assertIsInstance(opened_struct["b"][1], SharedMemoryArray) + np.testing.assert_array_equal(opened_struct["b"][1], arr) + self.assertTrue(opened_struct["b"][1]._unlink_on_del) + self.assertEqual(opened_struct["c"], 123) + + def test_copy_and_open_shm_min_size(self): + arr = np.arange(10).astype(np.int32) # 40 bytes + shm_struct = copy_to_shm(arr, min_size=100) + self.assertIsInstance(shm_struct, np.ndarray) + np.testing.assert_array_equal(shm_struct, arr) + shm_struct = copy_to_shm(arr, min_size=10) + self.assertIsInstance(shm_struct, SharedMemoryArrayMetadata) + opened_struct = open_from_shm(shm_struct) + self.assertIsInstance(opened_struct, SharedMemoryArray) + np.testing.assert_array_equal(opened_struct, arr) + self.assertTrue(opened_struct._unlink_on_del) + + def test_unlink_shm(self): + arr = np.arange(10).astype(np.int32) + arr2 = np.arange(5).astype(np.int32) + struct = {"a": arr, "b": [arr2, arr], "c": 123} + shm_struct = copy_to_shm(struct) + names = [ + shm_struct["a"].name, + shm_struct["b"][0].name, + shm_struct["b"][1].name, + ] + # Check that SHMs exist. + for name in names: + self.assertIsNotNone(shared_memory.SharedMemory(name=name, create=False)) + + unlink_shm(shm_struct) + + for name in names: + with self.assertRaises(FileNotFoundError): + shared_memory.SharedMemory(name=name, create=False) + + def test_advanced_indexing_returns_numpy_array(self): + shm_arr = SharedMemoryArray((10, 2), np.int32) + shm_arr.unlink_on_del() + # Slicing returns a view backed by shared memory: + sliced = shm_arr[0:2] + self.assertIsInstance(sliced, SharedMemoryArray) + self.assertIsNotNone(sliced.shm) + + # Advanced indexing returns a regular NumPy array: + advanced = shm_arr[[0, 2]] + self.assertNotIsInstance(advanced, SharedMemoryArray) + self.assertIsInstance(advanced, np.ndarray) + + +if __name__ == "__main__": + absltest.main()