"""GPU memory management utilities for coordinating CuBIE allocations.
This module provides the :class:`MemoryManager` singleton that
coordinates GPU memory allocation, stream usage, and automatic
chunking across registered instances.
Published Classes
-----------------
:class:`MemoryManager`
Singleton interface coordinating GPU memory allocation and stream
usage.
>>> mgr = MemoryManager()
:class:`InstanceMemorySettings`
Per-instance registry entry tracking allocations and hooks.
Published Constants
-------------------
:data:`ALL_MEMORY_MANAGER_PARAMETERS`
Parameter set accepted by the memory manager configuration.
Module-Level Functions
----------------------
:func:`get_portioned_request_size`
Calculate chunkable and unchunkable byte totals for a request
dictionary.
:func:`is_request_chunkable`
Determine whether a single :class:`ArrayRequest` can be chunked.
:func:`replace_with_chunked_size`
Replace the run axis in a shape tuple with a chunked size.
Notes
-----
Chunking is performed along the run axis to handle batches that
exceed available GPU memory. The chunking process is automatic and
coordinated across all instances in a stream group.
See Also
--------
:class:`~cubie.memory.array_requests.ArrayRequest`
Describes a single allocation request.
:class:`~cubie.memory.array_requests.ArrayResponse`
Reports allocation outcomes including chunking metadata.
:class:`~cubie.memory.stream_groups.StreamGroups`
Manages CUDA stream groups used by the memory manager.
"""
from collections import deque
from tempfile import mkstemp
from threading import Lock
from functools import cache, partial
from typing import Any, Optional, Callable, Dict, Set, Tuple, Union
from warnings import warn
from copy import deepcopy
from inspect import ismethod
from weakref import WeakMethod, finalize, ref as weakref_ref
import ctypes
import os
import sys
from cubie.cache_root import get_cache_root
from cubie._cudasim_extensions import (
cuda,
CudaSupportError,
DeviceNDArray,
Stream,
)
from cubie._utils import getype_validator, opt_getype_validator
from attrs import define, Factory as attrsFactory, field
from attrs.validators import (
in_ as attrsval_in,
instance_of as attrsval_instance_of,
optional as attrsval_optional,
)
from numpy import (
ceil as np_ceil,
dtype as np_dtype,
memmap as np_memmap,
ndarray,
floor as np_floor,
zeros as np_zeros,
)
from numpy.typing import DTypeLike
from math import prod
from cubie.memory.driver_memory import (
flush_deferred_frees,
page_locked_block,
pool_idle_bytes,
stream_idle,
stream_ordered_buffer,
)
from cubie.memory.stream_groups import StreamGroups
from cubie.memory.array_requests import ArrayRequest, ArrayResponse
# Recognised configuration parameters for memory manager settings.
# These keys mirror the solver API so helpers can filter keyword
# arguments consistently.
ALL_MEMORY_MANAGER_PARAMETERS = {
"memory_manager",
"stream_group",
"mem_proportion",
}
"""Solver memory keyword names."""
MIN_AUTOPOOL_SIZE = 0.05
HOST_SPILL_FRACTION = 0.8
"""Fraction of total system RAM available to host arrays."""
HOST_OS_RESERVE_BYTES = 512 * 1024**2
"""Available RAM staging growth leaves to the OS; a chosen margin."""
HOST_STAGING_BYTES = 64 * 1024**2
"""Maximum pinned staging bytes used by one host transfer.
64 MiB is large enough to reach full PCIe transfer bandwidth while
bounding the pinned footprint of a chunked or spilled solve.
"""
STAGING_POOL_DEPTH = 8
"""Maximum in-flight pinned staging buffers per label."""
CHUNK_HEADROOM_FRACTION = 0.02
"""Fraction of available memory chunk sizing leaves unallocated."""
ALLOCATION_GRANULE_BYTES = 32 * 1024**2
"""Reserve granule of the stream-ordered device pool."""
class NoCudaDeviceError(RuntimeError):
"""Raised by a sizing decision when no device is available."""
def _is_no_device_error(error: Exception) -> bool:
"""Return whether ``error`` signals an absent CUDA device."""
if isinstance(error, CudaSupportError):
return True
return isinstance(error, ValueError) and str(error).startswith(
"not enough values to unpack"
)
if sys.platform == "win32":
class _MemoryStatusEx(ctypes.Structure):
"""Layout of the Win32 ``MEMORYSTATUSEX`` structure."""
_fields_ = [
("dwLength", ctypes.c_ulong),
("dwMemoryLoad", ctypes.c_ulong),
("ullTotalPhys", ctypes.c_ulonglong),
("ullAvailPhys", ctypes.c_ulonglong),
("ullTotalPageFile", ctypes.c_ulonglong),
("ullAvailPageFile", ctypes.c_ulonglong),
("ullTotalVirtual", ctypes.c_ulonglong),
("ullAvailVirtual", ctypes.c_ulonglong),
("ullAvailExtendedVirtual", ctypes.c_ulonglong),
]
def _memory_status() -> "_MemoryStatusEx":
"""Return the filled Win32 ``MEMORYSTATUSEX`` structure."""
status = _MemoryStatusEx()
status.dwLength = ctypes.sizeof(_MemoryStatusEx)
if not ctypes.windll.kernel32.GlobalMemoryStatusEx(
ctypes.byref(status)
):
raise ctypes.WinError()
return status
@cache
def total_system_ram() -> int:
"""Return total physical RAM in bytes."""
if sys.platform == "win32":
return int(_memory_status().ullTotalPhys)
return os.sysconf("SC_PHYS_PAGES") * os.sysconf("SC_PAGE_SIZE")
def available_system_ram() -> int:
"""Return available physical RAM in bytes, including
reclaimable page cache on Linux."""
if sys.platform == "win32":
return int(_memory_status().ullAvailPhys)
if sys.platform == "linux":
with open("/proc/meminfo") as meminfo:
for line in meminfo:
if line.startswith("MemAvailable:"):
return int(line.split()[1]) * 1024
return os.sysconf("SC_AVPHYS_PAGES") * os.sysconf("SC_PAGE_SIZE")
def host_headroom_bytes() -> int:
"""Return available RAM above the OS reserve."""
return available_system_ram() - HOST_OS_RESERVE_BYTES
def _remove_spill_file(mapping: Any, path: str) -> None:
"""Close and delete one spill file.
Runs as a garbage-collection finalizer, where raising is not
possible, so a filesystem failure is reported as a warning.
"""
try:
mapping.close()
os.remove(path)
except OSError as error: # pragma: no cover - filesystem failure
warn(f"Could not remove spill file '{path}': {error}", ResourceWarning)
def c_contiguous_view(
buffer: Any, shape: Tuple[int, ...], dtype: DTypeLike
) -> Any:
"""View the start of a flat byte device buffer as a C array."""
itemsize = np_dtype(dtype).itemsize
strides = []
step = itemsize
for extent in reversed(shape):
strides.append(step)
step *= extent
return DeviceNDArray(
tuple(shape),
tuple(reversed(strides)),
np_dtype(dtype),
stream=buffer.stream,
gpu_data=buffer.gpu_data,
)
def placeholder_invalidate() -> None:
"""
Default invalidate hook placeholder that performs no operations.
"""
pass
def placeholder_dataready(response: ArrayResponse) -> None:
"""
Default placeholder data ready hook that performs no operations.
Parameters
----------
response
Array response object (unused).
"""
pass
class _WeakCallable:
"""Callable wrapper that holds bound methods weakly.
Registered instances supply bound methods as registry hooks; a
strong reference to those methods would keep the instance alive
for the lifetime of the registry. Bound methods are therefore
stored through :class:`weakref.WeakMethod`, while plain functions
are stored directly. Calling a wrapper whose referent has been
garbage collected is a no-op.
Parameters
----------
func
Callable to wrap. An existing wrapper is copied rather than
double-wrapped.
"""
def __init__(self, func: Callable) -> None:
if isinstance(func, _WeakCallable):
self._weak = func._weak
self._strong = func._strong
elif ismethod(func):
self._weak = WeakMethod(func)
self._strong = None
else:
self._weak = None
self._strong = func
def target(self) -> Optional[Callable]:
"""Return the wrapped callable, or None once collected."""
if self._weak is not None:
return self._weak()
return self._strong
def __call__(self, *args: Any, **kwargs: Any) -> Any:
target = self.target()
if target is None:
return None
return target(*args, **kwargs)
# Unhashable by design: equality tracks the referent, which can
# be collected mid-lifetime, so no stable hash exists.
__hash__ = None
def __eq__(self, other: object) -> bool:
if isinstance(other, _WeakCallable):
return self.target() == other.target()
return self.target() == other
def _ensure_cuda_context() -> None:
"""
Ensure CUDA context is initialized before memory operations.
This function validates that a CUDA context exists and is functional,
triggering initialization if needed. If the context cannot be created
or is in a bad state, it raises a clear exception rather than causing
a segfault.
Raises
------
RuntimeError
If CUDA context cannot be initialized or is not functional.
"""
try:
# Attempt to access current context - triggers creation if
# needed.
ctx = cuda.current_context()
if ctx is None:
raise RuntimeError(
"CUDA context is None - GPU may not be accessible"
)
# Skip memory info check for performance; context existence
# is sufficient validation for most operations
except Exception as e:
# Provide helpful error message instead of segfault
raise RuntimeError(
f"Failed to initialize or verify CUDA context: {e}. "
"This may indicate GPU driver issues, insufficient "
"permissions, or the GPU may be in an unrecoverable "
"state. Try restarting the process or checking GPU "
"availability."
) from e
# These will be keys to a dict, so must be hashable: eq=False
@define(eq=False)
class InstanceMemorySettings:
"""
Memory registry information for a registered instance.
Parameters
----------
proportion
Proportion of total VRAM assigned to this instance.
allocations
Dictionary of current allocations keyed by label.
buffers
Device buffer behind each device allocation, keyed by label.
invalidate_hook
Function to call when CUDA memory system changes occur.
allocation_ready_hook
Function to call when allocations are ready.
cap
Maximum allocatable bytes for this instance.
instance_ref
Weak reference to the registered instance, used to detect
and purge entries whose instance has been collected.
Attributes
----------
proportion : float
Proportion of total VRAM assigned to this instance.
allocations : dict
Dictionary of current allocations keyed by array label.
buffers : dict
Flat device buffer each device allocation views, keyed by
label. A later request that fits reuses it.
invalidate_hook : callable
Function to call when CUDA memory system changes.
allocation_ready_hook : callable
Function to call when allocations are ready.
cap : int or None
Maximum allocatable bytes for this instance.
instance_ref : weakref.ref or None
Weak reference to the registered instance.
Properties
----------
allocated_bytes : int
Bytes held for the instance: device buffers at full size plus
other allocations.
Notes
-----
The allocations dictionary serves both as a "keepalive" reference and a way
to calculate total allocated memory. The invalidate_hook is called when the
allocator/memory manager changes, requiring arrays and kernels to be
re-allocated or redefined.
Bound-method hooks are stored weakly so the registry never keeps
a registered instance alive; once the instance is collected the
hooks become no-ops and the entry is purged by the manager.
"""
proportion: float = field(
default=1.0, validator=attrsval_instance_of(float)
)
allocations: dict = field(
default=attrsFactory(dict), validator=attrsval_instance_of(dict)
)
buffers: dict = field(
default=attrsFactory(dict), validator=attrsval_instance_of(dict)
)
invalidate_hook: Callable[[], None] = field(
default=placeholder_invalidate,
converter=_WeakCallable,
validator=attrsval_instance_of(Callable),
)
allocation_ready_hook: Callable[[ArrayResponse], None] = field(
default=placeholder_dataready,
converter=_WeakCallable,
)
cap: Optional[int] = field(
default=None, validator=attrsval_optional(attrsval_instance_of(int))
)
instance_ref: Optional[weakref_ref] = field(
default=None,
validator=attrsval_optional(attrsval_instance_of(weakref_ref)),
)
last_stream: Optional[Any] = field(default=None)
submitting: bool = field(
default=False, validator=attrsval_instance_of(bool)
)
completion_event: Optional[Any] = field(default=None)
# register() always assigns an owner id; registrations sharing one
# owner id are evicted together or not at all.
owner_id: Optional[int] = field(default=None)
last_used: int = field(default=0, validator=attrsval_instance_of(int))
def free(self, key: str) -> None:
"""Free an allocation by key.
Parameters
----------
key
Label of the allocation to free.
Notes
-----
Emits a warning if the key is not found in allocations.
"""
self.buffers.pop(key, None)
if key in self.allocations:
del self.allocations[key]
else:
warn(
f"Attempted to free allocation for {key}, but "
f"it was not found in the allocations list."
)
def free_all(self) -> None:
"""Release allocations, then sync their last stream.
The sync returns freed pool memory to the device.
"""
self.allocations.clear()
self.buffers.clear()
if self.last_stream is not None:
self.last_stream.synchronize()
@property
def allocated_bytes(self) -> int:
"""Bytes held: device buffers at full size plus other arrays."""
total = 0
for key, arr in self.allocations.items():
buffer = self.buffers.get(key)
total += arr.nbytes if buffer is None else buffer.nbytes
return total
@property
def work_complete(self) -> bool:
"""Return whether the owner's submitted CUDA work is complete."""
if self.submitting:
return False
if self.completion_event is None:
return True
return bool(self.completion_event.query())
[docs]
@define
class MemoryManager:
"""Singleton interface coordinating GPU memory allocation and
stream usage.
Parameters
----------
registry
Registry mapping instance identifiers to their memory
settings.
stream_groups
Manager for organising instances into stream groups.
Attributes
----------
totalmem
Total GPU memory in bytes as of the last
:meth:`probe_device`, or ``None`` when no device answered.
Notes
-----
The manager accepts :class:`ArrayRequest` objects and returns
:class:`ArrayResponse` instances that reference allocated arrays
and chunking information. Active mode enforces per-instance VRAM
proportions while passive mode mirrors standard allocation
behaviour using chunking only when necessary.
Construction succeeds without a device: the manager stays
unsized and every decision needing a byte figure reprobes, then
raises :class:`NoCudaDeviceError` if no device answers.
See Also
--------
:class:`~cubie.memory.array_requests.ArrayRequest`
Describes a single allocation request.
:class:`~cubie.memory.array_requests.ArrayResponse`
Reports allocation outcomes.
:class:`~cubie.memory.stream_groups.StreamGroups`
Manages CUDA stream groups.
"""
# Device-read, never caller-supplied.
totalmem: Optional[int] = field(
default=None,
init=False,
validator=attrsval_optional(attrsval_instance_of(int)),
)
registry: dict[int, InstanceMemorySettings] = field(
default=attrsFactory(dict),
validator=attrsval_optional(attrsval_instance_of(dict)),
)
stream_groups: StreamGroups = field(default=attrsFactory(StreamGroups))
_mode: str = field(
default="passive", validator=attrsval_in(["passive", "active"])
)
_auto_pool: list[int] = field(
default=attrsFactory(list), validator=attrsval_instance_of(list)
)
_manual_pool: list[int] = field(
default=attrsFactory(list), validator=attrsval_instance_of(list)
)
_queued_allocations: Dict[str, Dict] = field(
default=attrsFactory(dict), validator=attrsval_instance_of(dict)
)
# Chunk parameters per (stream group, owner id): the partition a
# solver's live device arrays are laid out for.
_group_chunk_parameters: Dict[Tuple[str, int], Tuple[int, int]] = field(
default=attrsFactory(dict), validator=attrsval_instance_of(dict)
)
_usage_clock: int = field(default=0, init=False)
# Teardowns recorded by garbage-collection finalizers, run at the
# manager's next entry point. GC can fire inside any allocation —
# including mid-iteration over the registry, or on the transfer
# watcher's own thread — so finalizers must not deregister (or
# join threads) directly; they append here instead.
_pending_teardowns: list = field(factory=list, init=False)
# Cumulative pinned ceiling; None resolves to total VRAM, and
# stays None with no device.
pinned_max_bytes: Optional[int] = field(
default=None,
validator=opt_getype_validator(int, 0),
)
# Physical bytes withheld from chunk sizing: the pool's granule.
allocation_granule_bytes: int = field(
default=ALLOCATION_GRANULE_BYTES,
validator=getype_validator(int, 0),
)
# Pinned bytes of reachable arrays; finalizers queue releases.
_pinned_lock: Lock = field(factory=Lock, init=False)
_pinned_live_bytes: int = field(default=0, init=False)
_pinned_releases: deque = field(factory=deque, init=False)
# Idle pinned blocks: [block, nbytes, generation idle since].
_idle_pinned: list = field(factory=list, init=False)
_pinned_generation: int = field(default=0, init=False)
# Cause for the NoCudaDeviceError a sizing decision raises.
_device_probe_error: Optional[BaseException] = field(
default=None, init=False
)
def __attrs_post_init__(self) -> None:
"""Read device memory, leaving sizes unset without a device."""
self.registry = {}
self.probe_device()
[docs]
def probe_device(self) -> None:
"""Read the device's memory size.
An absent device stores its error and leaves the sizes
``None``.
Raises
------
Exception
The probe's own error, when it does not signal an absent
device.
"""
try:
_, total = self.get_memory_info()
except Exception as error:
if not _is_no_device_error(error):
raise
self._device_probe_error = error
total = None
else:
self._device_probe_error = None
self.totalmem = total
if self.pinned_max_bytes is None and total is not None:
self.pinned_max_bytes = total
[docs]
def _cap_bytes(self, proportion: float) -> Optional[int]:
"""Bytes for ``proportion`` of VRAM; ``None`` with no device."""
if self.totalmem is None:
return None
return int(proportion * self.totalmem)
[docs]
def _require_device(self) -> None:
"""Reprobe an unsized manager, then require a device size.
Raises
------
NoCudaDeviceError
If the device probe failed, chained to its error.
"""
if self.totalmem is None:
self.probe_device()
if self.totalmem is not None:
return
raise NoCudaDeviceError(
"the memory manager found no CUDA device, so it cannot "
"size an allocation"
) from self._device_probe_error
[docs]
def register(
self,
instance: object,
proportion: Optional[float] = None,
invalidate_cache_hook: Callable = placeholder_invalidate,
allocation_ready_hook: Callable = placeholder_dataready,
stream_group: str = "default",
owner: Optional[object] = None,
) -> None:
"""
Register an instance and configure its memory allocation settings.
Parameters
----------
instance
Instance to register for memory management.
proportion
Proportion of VRAM to allocate (0.0 to 1.0). When omitted, the
instance joins the automatic allocation pool.
invalidate_cache_hook
Function to call when CUDA memory system changes occur.
allocation_ready_hook
Function to call when allocations are ready.
stream_group
Name of the stream group to assign the instance to.
owner
Eviction unit for this registration. A solver kernel
passes itself when registering its input and output array
managers, so pressure evicts the whole solver or nothing.
Defaults to the instance itself.
Raises
------
ValueError
If instance is already registered or proportion is not
between 0 and 1.
"""
self._purge_dead_instances()
instance_id = id(instance)
if instance_id in self.registry:
raise ValueError("Instance already registered")
try:
instance_ref = weakref_ref(instance)
except TypeError:
instance_ref = None
owner_id = instance_id if owner is None else id(owner)
settings = InstanceMemorySettings(
invalidate_hook=invalidate_cache_hook,
allocation_ready_hook=allocation_ready_hook,
instance_ref=instance_ref,
owner_id=owner_id,
)
self.stream_groups.add_instance(instance, stream_group)
self.registry[instance_id] = settings
if proportion:
if not 0 <= proportion <= 1:
raise ValueError("Proportion must be between 0 and 1")
self._add_manual_proportion(instance, proportion)
else:
self._add_auto_proportion(instance)
[docs]
def update(
self,
instance: object,
updates_dict: Optional[Dict[str, Any]] = None,
silent: bool = False,
**kwargs: Any,
) -> Set[str]:
"""Update a registered instance's memory settings.
Parameters
----------
instance
Registered instance to update.
updates_dict
Setting names to new values: ``stream_group``,
``mem_proportion`` (``None`` selects the automatic limit)
and ``memory_manager`` (this manager only); ``None`` for
the other two changes nothing.
silent
Ignore unknown names instead of raising.
**kwargs
Further updates.
Returns
-------
Set[str]
The recognised names.
Raises
------
KeyError
Unknown names when not ``silent``.
ValueError
A different memory manager.
"""
updates = {**(updates_dict or {}), **kwargs}
recognised = set()
if "memory_manager" in updates:
manager = updates["memory_manager"]
if manager is not None and manager is not self:
raise ValueError(
"A registered instance cannot change memory manager."
)
recognised.add("memory_manager")
if "stream_group" in updates:
group = updates["stream_group"]
if group is not None and group != self.get_stream_group(instance):
self.change_stream_group(instance, group)
recognised.add("stream_group")
if "mem_proportion" in updates:
proportion = updates["mem_proportion"]
if proportion is None:
self.set_auto_limit_mode(instance)
else:
self.set_manual_proportion(instance, proportion)
recognised.add("mem_proportion")
unrecognised = set(updates) - recognised
if unrecognised and not silent:
raise KeyError(f"Unrecognized parameters: {sorted(unrecognised)}")
return recognised
[docs]
def get_registration(self, instance: object) -> InstanceMemorySettings:
"""Return the registry entry for a registered instance.
Parameters
----------
instance
Registered instance to look up.
Raises
------
KeyError
If the instance is not registered.
"""
return self.registry[id(instance)]
[docs]
def set_limit_mode(self, mode: str) -> None:
"""
Set the memory allocation limiting mode.
Parameters
----------
mode
Either ``"passive"`` or ``"active"`` memory management mode.
Raises
------
ValueError
If mode is not "passive" or "active".
"""
if mode not in ["passive", "active"]:
raise ValueError(f"Unknown mode: {mode}")
self._mode = mode
[docs]
def get_stream(self, instance: object) -> object:
"""
Get the CUDA stream associated with an instance.
Parameters
----------
instance
Instance to retrieve the stream for.
Returns
-------
object
CUDA stream associated with the instance.
"""
return self.stream_groups.get_stream(instance)
[docs]
def get_group_stream(self, group: str = "default") -> Union[Stream, int]:
"""
Get the dedicated stream for a named group, creating it if needed.
Parameters
----------
group
Name of the stream group.
Returns
-------
Stream
The group's dedicated CUDA stream. Because each process
owns its own manager, this stream is private to the
process; synchronizing it never orders against the
device-wide default stream.
"""
return self.stream_groups.get_group_stream(group)
[docs]
def change_stream_group(self, instance: object, new_group: str) -> None:
"""Move the owner's registrations, queued requests and partition.
Parameters
----------
instance
Instance to move.
new_group
Name of the new stream group.
"""
old_group = self.get_stream_group(instance)
owner_id = self.registry[id(instance)].owner_id
queued = self._queued_allocations.get(old_group, {})
members = list(
self.stream_groups.get_instances_in_group(old_group)
)
for instance_id in members:
if not self._owned_by(instance_id, owner_id):
continue
self.stream_groups.change_group(instance_id, new_group)
if instance_id in queued:
self._queued_allocations.setdefault(new_group, {})[
instance_id
] = queued.pop(instance_id)
if not queued:
self._queued_allocations.pop(old_group, None)
partition = self._group_chunk_parameters.pop(
(old_group, owner_id), None
)
if partition is not None:
self._group_chunk_parameters[(new_group, owner_id)] = partition
[docs]
def reinit_streams(self) -> None:
"""
Reinitialise all streams after a CUDA context reset.
"""
self.stream_groups.reinit_streams()
for settings in self.registry.values():
settings.completion_event = None
[docs]
def invalidate_all(self) -> None:
"""
Call each invalidate hook and release all allocations.
"""
self.free_all()
for registered_instance in self.registry.values():
registered_instance.invalidate_hook()
[docs]
def set_manual_proportion(
self, instance: object, proportion: float
) -> None:
"""
Set manual allocation proportion for an instance.
If instance is currently in the auto-allocation pool, shift it to
manual.
Parameters
----------
instance
Instance to update proportion for.
proportion
New proportion between 0 and 1.
Raises
------
ValueError
If proportion is not between 0 and 1.
"""
self._purge_dead_instances()
instance_id = id(instance)
if proportion < 0 or proportion > 1:
raise ValueError("Proportion must be between 0 and 1")
if instance_id in self._auto_pool:
self._auto_pool.remove(instance_id)
else:
self._manual_pool.remove(instance_id)
self._add_manual_proportion(instance, proportion)
[docs]
def set_manual_limit_mode(
self, instance: object, proportion: float
) -> None:
"""
Convert an auto-limited instance to manual allocation mode.
Parameters
----------
instance
Instance to convert to manual mode.
proportion
Memory proportion to assign (0.0 to 1.0).
Notes
-----
If the instance is already in the manual pool, this is a no-op.
"""
self._purge_dead_instances()
instance_id = id(instance)
if instance_id in self._manual_pool:
return
self._auto_pool.remove(instance_id)
self._add_manual_proportion(instance, proportion)
[docs]
def set_auto_limit_mode(self, instance: object) -> None:
"""
Convert a manual-limited instance to auto allocation mode.
Parameters
----------
instance
Instance to convert to auto mode.
Notes
-----
If the instance is already in the auto pool, this is a no-op.
"""
self._purge_dead_instances()
instance_id = id(instance)
settings = self.registry[instance_id]
if instance_id in self._auto_pool:
return
self._manual_pool.remove(instance_id)
settings.proportion = self._add_auto_proportion(instance)
[docs]
def proportion(self, instance: object) -> float:
"""
Get the maximum proportion of VRAM allocated to an instance.
Parameters
----------
instance
Instance to query.
Returns
-------
float
Proportion of VRAM allocated to this instance.
"""
instance_id = id(instance)
return self.registry[instance_id].proportion
[docs]
def manual_proportion(self, instance: object) -> Optional[float]:
"""Return an instance's reserved proportion; ``None`` if auto.
Parameters
----------
instance
Instance to query.
Returns
-------
float or None
Manual proportion, or ``None`` for auto-pool instances.
"""
instance_id = id(instance)
if instance_id in self._auto_pool:
return None
return self.registry[instance_id].proportion
[docs]
def cap(self, instance: object) -> Optional[int]:
"""
Get the maximum allocatable bytes for an instance.
Parameters
----------
instance
Instance to query.
Returns
-------
int or None
Maximum allocatable bytes for this instance.
"""
instance_id = id(instance)
settings = self.registry.get(instance_id)
return settings.cap
@property
def manual_pool_proportion(self):
"""Total proportion of VRAM currently assigned manually."""
self._purge_dead_instances()
manual_settings = [
self.registry[instance_id] for instance_id in self._manual_pool
]
pool_proportion = sum(
[settings.proportion for settings in manual_settings]
)
return pool_proportion
@property
def auto_pool_proportion(self):
"""Total proportion of VRAM currently distributed automatically."""
self._purge_dead_instances()
auto_settings = [
self.registry[instance_id] for instance_id in self._auto_pool
]
pool_proportion = sum(
[settings.proportion for settings in auto_settings]
)
return pool_proportion
[docs]
def _add_manual_proportion(
self, instance: object, proportion: float
) -> None:
"""
Add an instance to the manual allocation pool with the specified
proportion.
Parameters
----------
instance
Instance to add to manual allocation pool.
proportion
Memory proportion to assign (0.0 to 1.0).
Raises
------
ValueError
If manual proportion would exceed total available memory or leave
insufficient memory for auto-allocated processes.
Warnings
--------
UserWarning
If manual proportion leaves less than 5% of memory for auto
allocation.
Notes
-----
Updates the instance's proportion and cap, then rebalances the auto
pool. Enforces minimum auto pool size constraints.
"""
instance_id = id(instance)
new_manual_pool_size = self.manual_pool_proportion + proportion
if new_manual_pool_size > 1.0:
raise ValueError(
"Manual proportion would exceed total available memory"
)
elif new_manual_pool_size > 1.0 - MIN_AUTOPOOL_SIZE:
if len(self._auto_pool) > 0:
raise ValueError(
"Manual proportion would leave less than 5% "
"of memory for auto-allocated processes. If "
"this is desired, adjust MIN_AUTOPOOL_SIZE in "
"mem_manager.py."
)
else:
warn(
"Manual proportion leaves less than 5% of memory for "
"auto allocation if management mode == 'active'."
)
self._manual_pool.append(instance_id)
self.registry[instance_id].proportion = proportion
self.registry[instance_id].cap = self._cap_bytes(proportion)
self._rebalance_auto_pool()
[docs]
def _add_auto_proportion(self, instance: object) -> float:
"""
Add an instance to the auto allocation pool with equal share.
Parameters
----------
instance
Instance to add to auto allocation pool.
Returns
-------
float
Proportion assigned to this instance.
Raises
------
ValueError
If available auto-allocation pool is less than minimum required
size.
Notes
-----
Splits the non-manually-allocated portion of VRAM equally among all
auto-allocated instances. Triggers rebalancing of the auto pool.
"""
instance_id = id(instance)
autopool_available = 1.0 - self.manual_pool_proportion
if autopool_available <= MIN_AUTOPOOL_SIZE:
raise ValueError(
"Available auto-allocation pool is less than "
"5% of total due to manual allocations. If "
"this is desired, adjust MIN_AUTOPOOL_SIZE in "
"mem_manager.py."
)
self._auto_pool.append(instance_id)
self._rebalance_auto_pool()
return self.registry[instance_id].proportion
[docs]
def defer_teardown(self, teardown: Callable[[], None]) -> None:
"""Record a teardown to run at the manager's next entry point.
Garbage-collection finalizers call this instead of
deregistering directly: GC runs inside whatever allocation
triggered it — possibly while this manager iterates its
registry, possibly on the transfer watcher's own thread — so
the callback only appends. ``_purge_dead_instances`` runs the
recorded teardowns in normal call context.
"""
self._pending_teardowns.append(teardown)
[docs]
def _purge_dead_instances(self) -> None:
"""
Drop registry entries whose instance has been collected.
Registered instances are held weakly. Once an instance is
garbage collected, its manual or auto reservation is
released, its stream-group membership is removed, and any
allocations it still had queued are discarded. Teardowns
recorded by GC finalizers run first, here, in normal call
context.
"""
while self._pending_teardowns:
self._pending_teardowns.pop()()
dead_ids = [
instance_id
for instance_id, settings in self.registry.items()
if settings.instance_ref is not None
and settings.instance_ref() is None
]
for instance_id in dead_ids:
self._drop_instance(instance_id)
if dead_ids:
# Freed reservations flow back to the surviving auto pool.
# The nested purge this triggers finds nothing dead, so
# the recursion terminates after one level.
self._rebalance_auto_pool()
[docs]
def _drop_instance(self, instance_id: int) -> None:
"""Free and deregister one instance."""
settings = self.registry.get(instance_id)
if settings is not None:
settings.free_all()
self.registry.pop(instance_id)
if instance_id in self._manual_pool:
self._manual_pool.remove(instance_id)
if instance_id in self._auto_pool:
self._auto_pool.remove(instance_id)
self.stream_groups.remove_instance(instance_id)
for queued in self._queued_allocations.values():
queued.pop(instance_id, None)
# Drop the owner's cached run partition.
for cache_key in [
key for key in self._group_chunk_parameters
if key[1] == instance_id
]:
del self._group_chunk_parameters[cache_key]
[docs]
def release_instance(
self, instance_id: int, settings: "InstanceMemorySettings"
) -> None:
"""Release a matching registered instance."""
if self.registry.get(instance_id) is not settings:
return
self._drop_instance(instance_id)
self._rebalance_auto_pool()
[docs]
def _owner_settings(self, owner_id: int) -> list[InstanceMemorySettings]:
"""Return registry entries owned by one client."""
return [
settings
for settings in self.registry.values()
if settings.owner_id == owner_id
]
[docs]
def begin_work(self, owner: object) -> None:
"""Mark an owner as submitting CUDA work.
Raises
------
RuntimeError
If the CUDA context is not usable.
"""
_ensure_cuda_context()
self._usage_clock += 1
for settings in self._owner_settings(id(owner)):
settings.submitting = True
settings.last_used = self._usage_clock
[docs]
def end_work(self, owner: object, stream: Stream) -> None:
"""Record completion of an owner's submitted CUDA work."""
owned = self._owner_settings(id(owner))
# The owner's registrations share one event, re-recorded each time.
event = None
for settings in owned:
if settings.completion_event is not None:
event = settings.completion_event
break
if event is None:
event = cuda.event()
event.record(stream)
for settings in owned:
settings.last_stream = stream
settings.completion_event = event
settings.submitting = False
[docs]
def _evict_idle_owners(
self, exclude_ids: set[int], required_bytes: int
) -> int:
"""Free the least-recently-used idle owners.
Whole owners are evicted, oldest first, until ``required_bytes``
are released. Returns the number of bytes actually released.
"""
excluded_owners = {
self.registry[instance_id].owner_id
for instance_id in exclude_ids
if instance_id in self.registry
}
# Group registrations into eviction units by owner id.
owners: Dict[int, list] = {}
for settings in self.registry.values():
owners.setdefault(settings.owner_id, []).append(settings)
candidates = []
for owner_id, owned in owners.items():
# Never evict the requester's own registrations.
if owner_id in excluded_owners:
continue
# Skip owners with submitted CUDA work still running.
if not all(settings.work_complete for settings in owned):
continue
allocated = sum(settings.allocated_bytes for settings in owned)
if allocated == 0:
continue
oldest_use = min(settings.last_used for settings in owned)
candidates.append((oldest_use, owned))
released = 0
for _, owned in sorted(candidates, key=lambda item: item[0]):
if released >= required_bytes:
break
for settings in owned:
released += settings.allocated_bytes
settings.invalidate_hook()
settings.free_all()
return released
[docs]
def _rebalance_auto_pool(self) -> None:
"""
Redistribute available memory equally among auto-allocated instances.
Notes
-----
Calculates the available proportion after manual allocations and
divides it equally among all instances in the auto pool. Updates
both proportion and cap for each auto-allocated instance.
"""
available_proportion = 1.0 - self.manual_pool_proportion
if len(self._auto_pool) == 0:
return
each_proportion = available_proportion / len(self._auto_pool)
cap = self._cap_bytes(each_proportion)
for instance_id in self._auto_pool:
self.registry[instance_id].proportion = each_proportion
self.registry[instance_id].cap = cap
[docs]
def free(self, array_label: str) -> None:
"""
Free an allocation by label across all instances.
Parameters
----------
array_label
Label of the allocation to free.
"""
for settings in self.registry.values():
if array_label in settings.allocations:
settings.free(array_label)
[docs]
def free_all(self) -> None:
"""
Free all allocations across all registered instances.
"""
for settings in self.registry.values():
settings.free_all()
[docs]
def _check_requests(self, requests: dict[str, ArrayRequest]) -> None:
"""
Validate that all requests are properly formatted.
Parameters
----------
requests
Dictionary of requests to validate.
Raises
------
TypeError
If requests is not a dict or contains invalid ArrayRequest objects.
"""
if not isinstance(requests, dict):
raise TypeError(
f"Expected dict for requests, got {type(requests)}"
)
for key, request in requests.items():
if not isinstance(request, ArrayRequest):
raise TypeError(
f"Expected ArrayRequest for {key}, got {type(request)}"
)
@property
def pinned_budget_bytes(self) -> int:
"""``pinned_max_bytes`` capped at the spill fraction of RAM.
Raises
------
NoCudaDeviceError
If the last device probe failed.
"""
self._require_device()
ram_cap = int(HOST_SPILL_FRACTION * total_system_ram())
return min(self.pinned_max_bytes, ram_cap)
@property
def pinned_live_bytes(self) -> int:
"""Pinned bytes currently backing reachable arrays."""
with self._pinned_lock:
self._apply_pinned_releases()
return self._pinned_live_bytes
@property
def pinned_idle_bytes(self) -> int:
"""Pinned bytes held for reuse by no reachable array."""
with self._pinned_lock:
self._apply_pinned_releases()
return sum(entry[1] for entry in self._idle_pinned)
[docs]
def _apply_pinned_releases(self) -> None:
"""Move collected pinned blocks to the idle list."""
while True:
try:
block, nbytes = self._pinned_releases.popleft()
except IndexError:
return
self._pinned_live_bytes -= nbytes
self._idle_pinned.append(
[block, nbytes, self._pinned_generation]
)
[docs]
def _group_streams_idle(self) -> bool:
"""Return whether every group stream has finished its work."""
return all(
stream_idle(stream)
for stream in self.stream_groups.streams.values()
)
[docs]
def _take_idle_pinned(self, nbytes: int) -> Optional[list]:
"""Claim the smallest reusable idle block that fits."""
generation = self._pinned_generation
streams_idle = self._group_streams_idle()
# A busy stream may still copy into a recently idled block.
fitting = [
entry for entry in self._idle_pinned
if entry[1] >= nbytes
and (streams_idle or entry[2] < generation)
]
if not fitting:
return None
entry = min(fitting, key=lambda item: item[1])
self._idle_pinned.remove(entry)
self._pinned_live_bytes += entry[1]
return entry
[docs]
def _reserve_pinned_bytes(self, nbytes: int, force: bool = False) -> bool:
"""Reserve ``nbytes`` against the pinned budget unless forced."""
with self._pinned_lock:
self._apply_pinned_releases()
budget = self.pinned_budget_bytes
idle = sum(entry[1] for entry in self._idle_pinned)
if self._pinned_live_bytes + idle + nbytes > budget:
# Free idle blocks now; this waits for the device.
self._idle_pinned.clear()
flush_deferred_frees()
if not force and self._pinned_live_bytes + nbytes > budget:
return False
self._pinned_live_bytes += nbytes
return True
[docs]
def release_idle_memory(self, keep_recent: bool = True) -> None:
"""Free stale idle blocks; ``keep_recent=False`` frees all."""
if keep_recent and not (self._idle_pinned or self._pinned_releases):
return
if not self._group_streams_idle():
return
with self._pinned_lock:
self._apply_pinned_releases()
generation = self._pinned_generation
idle = len(self._idle_pinned)
self._idle_pinned = [
entry for entry in self._idle_pinned
if keep_recent and entry[2] == generation
]
freed = len(self._idle_pinned) < idle
self._pinned_generation = generation + 1
if freed or not keep_recent:
flush_deferred_frees()
[docs]
def _on_pinned_released(self, block: Any, nbytes: int) -> None:
"""Queue a collected pinned array's block without locking."""
self._pinned_releases.append((block, nbytes))
[docs]
def allocate_pinned_array(
self,
shape: Tuple[int, ...],
dtype: DTypeLike,
force: bool = False,
) -> Optional[ndarray]:
"""Allocate one budget-accounted pinned host array.
Reuses the smallest reusable idle block that fits, else
reserves bytes and allocates a block. The block goes idle once
the array and every view of it are collected.
Parameters
----------
shape
Shape of the array to allocate.
dtype
Data type for the array elements.
force
Reserve even past the budget. A driver failure then
propagates instead of returning ``None``.
Returns
-------
numpy.ndarray or None
The pinned array, or ``None`` when the budget or the
driver refuses.
Raises
------
NoCudaDeviceError
If the last device probe failed.
"""
nbytes = max(int(prod(shape)) * np_dtype(dtype).itemsize, 1)
with self._pinned_lock:
self._apply_pinned_releases()
entry = self._take_idle_pinned(nbytes)
if entry is not None:
block, capacity = entry[0], entry[1]
else:
if not self._reserve_pinned_bytes(nbytes, force=force):
return None
try:
block = page_locked_block(nbytes)
except Exception:
# Driver refused: return the reservation to the budget.
with self._pinned_lock:
self._pinned_live_bytes -= nbytes
if force:
# Forced callers were promised pinned: re-raise.
raise
return None
capacity = nbytes
arr = ndarray(shape, dtype=dtype, buffer=block)
finalize(arr, self._on_pinned_released, block, capacity)
return arr
[docs]
def create_host_array(
self,
shape: tuple[int, ...],
dtype: DTypeLike,
memory_type: str = "pinned",
like: Optional[ndarray] = None,
) -> ndarray:
"""
Create a C-contiguous host array.
Parameters
----------
shape
Shape of the array to create.
dtype
Data type for the array elements.
memory_type
``"pinned"``, ``"host"``, or ``"memmap"``.
like
Optional source data.
Returns
-------
numpy.ndarray
C-contiguous host array; a :class:`numpy.memmap` in the
cache root when spilled. A ``"pinned"`` request whose
reservation or driver allocation fails lands pageable.
Raises
------
ValueError
If ``memory_type`` is not ``"pinned"``, ``"host"``, or
``"memmap"``.
"""
_ensure_cuda_context()
if memory_type not in ("pinned", "host", "memmap"):
raise ValueError(
f"memory_type must be 'pinned', 'host', or 'memmap', "
f"got '{memory_type}'"
)
if memory_type == "memmap":
arr = self._create_spill_array(shape, dtype)
elif memory_type == "pinned":
arr = self.allocate_pinned_array(shape, dtype)
if arr is None:
arr = np_zeros(shape, dtype=dtype)
elif like is None:
arr.fill(0.0)
else:
# zeros() maps untouched pages lazily, so a large pageable
# array costs nothing until the transfer writes it.
arr = np_zeros(shape, dtype=dtype)
if like is not None:
arr[:] = like
return arr
[docs]
def choose_host_memory_type(
self, nbytes: int, allow_pinned: bool = True
) -> str:
"""Pick the backing for a host array of ``nbytes`` bytes.
Memmap above ``HOST_SPILL_FRACTION`` of RAM, pinned within
``pinned_max_bytes``, else pageable.
Parameters
----------
nbytes
Size of the array in bytes.
allow_pinned
Permit the ``"pinned"`` choice; chunked staging passes
``False``.
Returns
-------
str
``"pinned"``, ``"host"``, or ``"memmap"``.
Raises
------
NoCudaDeviceError
If a pinned choice is reachable but no device answers
the probe.
"""
threshold = int(total_system_ram() * HOST_SPILL_FRACTION)
if nbytes > threshold:
return "memmap"
if not allow_pinned:
return "host"
self._require_device()
if nbytes <= self.pinned_max_bytes:
return "pinned"
return "host"
[docs]
def _create_spill_array(
self, shape: tuple[int, ...], dtype: DTypeLike
) -> np_memmap:
"""Create a disk-backed array in the cache root."""
directory = os.fspath(get_cache_root())
os.makedirs(directory, exist_ok=True)
handle, path = mkstemp(
prefix="cubie-spill-", suffix=".dat", dir=directory
)
os.close(handle)
arr = np_memmap(path, dtype=dtype, mode="w+", shape=shape)
cleanup = finalize(arr, _remove_spill_file, arr._mmap, path)
arr._cubie_spill_path = path
arr._cubie_spill_cleanup = cleanup
return arr
[docs]
def release_host_array(self, array: ndarray) -> None:
"""Release a spill-backed host array."""
cleanup = getattr(array, "_cubie_spill_cleanup", None)
if cleanup is None or not cleanup.alive:
return
path = array._cubie_spill_path
try:
array._mmap.close()
os.remove(path)
except OSError as error:
raise OSError(f"Could not remove spill file '{path}'") from error
cleanup.detach()
[docs]
def get_available_memory(self, group: str) -> int:
"""
Get available memory for an entire stream group.
Parameters
----------
group
Name of the stream group.
Returns
-------
int
Available memory in bytes for the group.
Warnings
--------
UserWarning
If group has used more than 95% of allocated memory.
Raises
------
NoCudaDeviceError
If no device answers the probe.
"""
self._require_device()
free, total = self.get_memory_info()
instances = self.stream_groups.get_instances_in_group(group)
if self._mode == "passive":
return free
else:
allocated = 0
cap = 0
for instance_id in instances:
allocated += self.registry[instance_id].allocated_bytes
cap += self.registry[instance_id].cap
headroom = cap - allocated
if headroom / cap < 0.05:
warn(
f"Stream group {group} has used more than 95% of it's "
"allotted memory already, and future requests will run "
"slowly/in many chunks"
)
return min(headroom, free)
[docs]
def get_memory_info(self) -> tuple[int, int]:
"""
Get free and total GPU memory information.
Returns
-------
tuple of int
(free_memory, total_memory) in bytes. Free memory includes
bytes the device pool holds but no array uses.
"""
free, total = cuda.current_context().get_memory_info()
return free + pool_idle_bytes(), total
[docs]
def get_stream_group(self, instance: object) -> str:
"""
Get the name of the stream group for an instance.
Parameters
----------
instance
Instance to query.
Returns
-------
str
Name of the stream group.
"""
return self.stream_groups.get_group(instance)
[docs]
def is_grouped(self, instance: object) -> bool:
"""
Check if instance is grouped with others in a named stream.
Parameters
----------
instance
Instance to check.
Returns
-------
bool
True if instance shares a stream group with other instances.
"""
group = self.get_stream_group(instance)
if group == "default":
return False
peers = self.stream_groups.get_instances_in_group(group)
if len(peers) == 1:
return False
return True
[docs]
def allocate_all(
self,
requests: dict[str, ArrayRequest],
instance_id: int,
stream: "cuda.cudadrv.driver.Stream",
settings: Optional[InstanceMemorySettings] = None,
) -> dict[str, object]:
"""
Allocate multiple arrays based on a dictionary of requests.
Parameters
----------
requests
Dictionary mapping labels to array requests.
instance_id
ID of the requesting instance.
stream
CUDA stream for the allocations.
settings
Registration to record the allocations in. Passing it
avoids a registry lookup that can fail when the client is
garbage collected between queueing and allocation.
Returns
-------
dict of str to object
Dictionary mapping labels to allocated arrays.
"""
responses = {}
instance_settings = (
settings if settings is not None else self.registry[instance_id]
)
instance_settings.last_stream = stream
for key, request in requests.items():
if request.memory == "device":
arr = self._device_view(
instance_settings, key, request, stream
)
else:
# Release the array this request replaces first.
if key in instance_settings.allocations:
instance_settings.free(key)
arr = self.allocate(
shape=request.shape,
dtype=request.dtype,
memory_type=request.memory,
stream=stream,
)
instance_settings.allocations[key] = arr
responses[key] = arr
return responses
[docs]
def _device_view(
self,
settings: InstanceMemorySettings,
key: str,
request: ArrayRequest,
stream: Stream,
) -> object:
"""View the label's buffer, replaced when small or off-stream."""
_ensure_cuda_context()
nbytes = prod(request.shape) * np_dtype(request.dtype).itemsize
buffer = settings.buffers.get(key)
if (
buffer is None
or buffer.nbytes < nbytes
or buffer.stream is not stream
):
# Drop every reference so the pool can reuse the bytes.
buffer = None
settings.buffers.pop(key, None)
settings.allocations.pop(key, None)
buffer = stream_ordered_buffer(max(nbytes, 1), stream)
settings.buffers[key] = buffer
return c_contiguous_view(buffer, request.shape, request.dtype)
[docs]
def allocate(
self,
shape: tuple[int, ...],
dtype: Callable,
memory_type: str,
stream: "cuda.cudadrv.driver.Stream" = 0,
) -> object:
"""
Allocate a single C-contiguous array with specified parameters.
Parameters
----------
shape
Shape of the array to allocate.
dtype
Constructor returning the precision object for the array elements.
memory_type
Type of memory: "device" or "pinned".
stream
Stream device memory is ordered on; ``0`` uses the
default group stream.
Returns
-------
object
Allocated GPU array.
Raises
------
ValueError
If memory_type is not "device" or "pinned".
"""
_ensure_cuda_context()
if memory_type == "device":
if not isinstance(stream, Stream):
stream = self.get_group_stream()
nbytes = prod(shape) * np_dtype(dtype).itemsize
buffer = stream_ordered_buffer(max(nbytes, 1), stream)
return c_contiguous_view(buffer, shape, dtype)
elif memory_type == "pinned":
# Pinned was requested by name: force, driver errors raise.
return self.allocate_pinned_array(shape, dtype, force=True)
else:
raise ValueError(f"Invalid memory type: {memory_type}")
[docs]
def queue_request(
self, instance: object, requests: dict[str, ArrayRequest]
) -> None:
"""
Queue allocation requests for batched stream group processing.
Parameters
----------
instance
The instance making the request.
requests
Dictionary mapping labels to array requests.
Raises
------
ValueError
If the instance registered without a live invalidate hook.
Allocation holders are eviction candidates, so they must
be able to drop handles when their buffers are freed.
Notes
-----
Requests are queued per stream group, allowing multiple components
to contribute to a single coordinated allocation that can be
optimally chunked together.
"""
self._check_requests(requests)
instance_id = id(instance)
settings = self.registry[instance_id]
if settings.invalidate_hook.target() in (
None,
placeholder_invalidate,
):
raise ValueError(
"Instances that request allocations must register a "
"live invalidate_cache_hook: allocated buffers are "
"evicted under VRAM pressure, and the hook is how the "
"instance drops its handles."
)
stream_group = self.get_stream_group(instance)
if self._queued_allocations.get(stream_group) is None:
self._queued_allocations[stream_group] = {}
self._queued_allocations[stream_group].update({instance_id: requests})
[docs]
def to_device(
self,
instance: object,
from_arrays: list[object],
to_arrays: list[object],
stream: Optional[Stream] = None,
) -> None:
"""
Copy data to device arrays using the instance's stream.
Parameters
----------
instance
Instance whose stream to use for copying.
from_arrays
Source arrays to copy from.
to_arrays
Destination device arrays to copy to.
"""
if stream is None:
stream = self.get_stream(instance)
self.registry[id(instance)].last_stream = stream
# Pinned host buffer -> device, streamed async H2D. The low-level
# driver copy skips copy_to_device's per-call np.array re-wrap and
# compatibility checks (~50us/call), which are unnecessary here: the
# source is an already-pinned, C-contiguous, size-matched buffer.
for i, from_array in enumerate(from_arrays):
if from_array.size == 0:
continue
# Sized by the pinned host buffer so the copy can never run
# past it, whatever the device allocation rounded up to.
cuda.cudadrv.driver.host_to_device(
to_arrays[i], from_array, from_array.nbytes,
stream=stream,
)
[docs]
def from_device(
self,
instance: object,
from_arrays: list[object],
to_arrays: list[object],
stream: Optional[Stream] = None,
) -> None:
"""
Copy data from device arrays using the instance's stream.
Parameters
----------
instance
Instance whose stream to use for copying.
from_arrays
Source device arrays to copy from.
to_arrays
Destination arrays to copy to.
"""
if stream is None:
stream = self.get_stream(instance)
self.registry[id(instance)].last_stream = stream
# Device -> pinned host buffer, streamed async D2H via the low-level
# driver copy (to_arrays are pinned, C-contiguous, size-matched).
for i, from_array in enumerate(from_arrays):
if from_array.size == 0:
continue
# Sized by the pinned host buffer so the copy can never run
# past it, whatever the device allocation rounded up to.
cuda.cudadrv.driver.device_to_host(
to_arrays[i], from_array, to_arrays[i].nbytes,
stream=stream,
)
[docs]
def sync_stream(
self, instance: object, stream: Optional[Stream] = None
) -> None:
"""
Synchronize the CUDA stream for an instance.
Parameters
----------
instance
Instance whose stream to synchronize.
"""
if stream is None:
settings = self.registry.get(id(instance))
stream = None if settings is None else settings.last_stream
if stream is None:
stream = self.get_stream(instance)
if stream == 0:
stream = self.get_stream(instance)
stream.synchronize()
[docs]
def allocate_queue(
self,
triggering_instance: object,
stream: Optional[Stream] = None,
) -> None:
"""
Process all queued requests for a stream group with coordinated
chunking.
Chunking is always performed along the run axis when memory
constraints require splitting the batch.
Parameters
----------
triggering_instance
The instance that triggered queue processing.
Notes
-----
Processes the pending requests of the triggering instance's
owner within its stream group, applying coordinated chunking
based on available memory, and calls allocation_ready_hook for
each of those instances with their results. Requests queued by
other owners in the group stay queued until their own owner
triggers. The owner's instances with no queued requests
receive an empty response carrying the owner's chunk
parameters. When nothing of the owner's is queued the call
returns at once.
"""
stream_group = self.get_stream_group(triggering_instance)
# Only the triggering owner's registrations take part.
owner_id = self.registry[id(triggering_instance)].owner_id
cache_key = (stream_group, owner_id)
peers = [
peer
for peer in self.stream_groups.get_instances_in_group(
stream_group
)
if self._owned_by(peer, owner_id)
]
group_queue = self._queued_allocations.get(stream_group, {})
queued_requests = {}
for instance_id in list(group_queue):
if self.registry.get(instance_id) is None:
# A dead registrant's request has no arrays to receive.
group_queue.pop(instance_id)
elif self._owned_by(instance_id, owner_id):
queued_requests[instance_id] = group_queue.pop(instance_id)
if not group_queue:
self._queued_allocations.pop(stream_group, None)
if not queued_requests:
return None
if stream is None:
stream = self.get_stream(triggering_instance)
for peer in peers:
self.registry[peer].last_stream = stream
# Get total_runs from first request
num_runs = 1
for requests_dict in queued_requests.values():
for request in requests_dict.values():
num_runs = request.total_runs
break
if num_runs > 1:
break
notaries = set(peers) - set(queued_requests.keys())
# Keep the partition a peer's arrays use if it holds this batch.
bound_to_cached = any(
self.registry[peer].allocations for peer in notaries
)
cached_parameters = self._group_chunk_parameters.get(cache_key)
if (
bound_to_cached
and cached_parameters is not None
and partition_covers(cached_parameters, num_runs)
):
chunk_length, num_chunks = cached_parameters
else:
chunk_length, num_chunks = self.get_chunk_parameters(
queued_requests, num_runs, stream_group
)
self._group_chunk_parameters[cache_key] = (
chunk_length,
num_chunks,
)
for instance_id, requests_dict in queued_requests.items():
# Resolve the registration once: a client can be garbage
# collected at any allocation, and its finalizer drops the
# registry entry mid-loop. The held settings object stays
# valid; a dead client's hook is a weak no-op and its
# arrays are released with the settings object.
settings = self.registry.get(instance_id)
if settings is None:
continue
chunked_shapes = self.compute_chunked_shapes(
requests_dict,
chunk_length,
)
chunked_requests = deepcopy(requests_dict)
for key, request in chunked_requests.items():
request.shape = chunked_shapes[key]
arrays = self.allocate_all(
chunked_requests,
instance_id,
stream=stream,
settings=settings,
)
response = ArrayResponse(
arr=arrays,
chunks=num_chunks,
chunk_length=chunk_length,
chunked_shapes=chunked_shapes,
)
settings.allocation_ready_hook(response)
for peer in notaries:
peer_settings = self.registry.get(peer)
if peer_settings is None:
# Collected during the allocation loop above.
continue
peer_settings.allocation_ready_hook(
ArrayResponse(
arr={},
chunks=num_chunks,
chunk_length=chunk_length,
chunked_shapes={},
)
)
return None
[docs]
def _owned_by(self, instance_id: int, owner_id: int) -> bool:
"""Return whether a registered instance belongs to ``owner_id``."""
settings = self.registry.get(instance_id)
return settings is not None and settings.owner_id == owner_id
[docs]
def get_chunk_parameters(
self,
requests: Dict[str, Dict],
axis_length: int,
stream_group: str,
) -> Tuple[int, int]:
"""
Calculate number of chunks and chunk size for a dict of array requests.
Chunking is performed along the run axis only.
Parameters
----------
requests
Dictionary mapping instance IDs to their array requests.
axis_length
Unchunked length of the chunking axis.
stream_group
Name of the stream group making the request.
Returns
-------
int, int
Length of chunked axis (``ceil(axis_length / num_chunks)``)
and number of chunks needed to fit the request.
Warnings
--------
UserWarning
If request exceeds available VRAM by more than 20x.
Raises
------
NoCudaDeviceError
If no device answers the probe.
Notes
-----
The request is offered ``min((1 - CHUNK_HEADROOM_FRACTION) ×
available, free - allocation_granule_bytes)`` bytes.
"""
self._require_device()
free, _ = self.get_memory_info()
available_memory = self.get_available_memory(stream_group)
cap_headroom = None
if self._mode == "active":
members = self.stream_groups.get_instances_in_group(stream_group)
cap_headroom = sum(
self.registry[member].cap
- self.registry[member].allocated_bytes
for member in members
)
chunkable_size, unchunkable_size = get_portioned_request_size(
requests,
)
request_size = chunkable_size + unchunkable_size
# A requester's current device buffers are replaced by this
# allocation, so their bytes are usable for it: without this
# credit a same-size reallocation reads as a shortage of its
# own footprint.
own_reclaimable = sum(
self.registry[instance_id].allocated_bytes
for instance_id in requests
if instance_id in self.registry
)
free_effective = free + own_reclaimable
# Evict only for a genuine physical VRAM shortage that eviction
# can fix. A configured cap (active mode) is a policy limit:
# when the request exceeds cap headroom the run chunks anyway,
# and evicting peers cannot raise the cap.
physical_shortage = request_size >= free_effective
cap_allows_request = (
cap_headroom is None or request_size < cap_headroom
)
if physical_shortage and cap_allows_request:
released = self._evict_idle_owners(
set(requests.keys()), request_size - free_effective + 1
)
free_effective += released
physical_headroom = (
free_effective
if cap_headroom is None
else min(free_effective, cap_headroom)
)
# Group accounting and the physical probe are both estimates;
# trust whichever allows more, since pool-held blocks satisfy
# allocations without showing up as free device memory.
available_memory = max(available_memory, physical_headroom)
# The granule floor applies to physical free memory only.
fractional_headroom = int(available_memory * CHUNK_HEADROOM_FRACTION)
allocatable = min(
available_memory - fractional_headroom,
free_effective - self.allocation_granule_bytes,
)
headroom = available_memory - allocatable
if request_size < allocatable:
return axis_length, 1 # No chunking needed
if free > 0 and request_size / free > 20:
warn(
"This request exceeds available VRAM by more than 20x. "
f"Available VRAM = {free}, request size = {request_size}.",
UserWarning,
)
# Check for all arrays unchunkable
if chunkable_size == 0:
raise ValueError(
f"All requested arrays are unchunkable, but request size "
f"({request_size}) exceeds available memory "
f"({available_memory}). Cannot proceed."
)
# Guard: nothing left to chunk after unchunkable arrays
available_to_chunk = allocatable - unchunkable_size
if available_to_chunk <= 0:
raise ValueError(
f"Unchunkable arrays require {unchunkable_size} "
f"bytes and chunk sizing withholds {headroom} bytes, "
f"but only {available_memory} bytes are available. "
"Cannot proceed."
)
chunk_ratio = chunkable_size / available_to_chunk
# Largest chunk that fits in the allocatable memory.
max_chunk_size = int(np_floor(axis_length / chunk_ratio))
if max_chunk_size == 0:
raise ValueError(
"Can't fit a single run in GPU VRAM. "
f"Available memory: {available_memory}. "
f"Request size: {request_size}. "
f"Chunkable request size: {chunkable_size}."
)
num_chunks = int(np_ceil(axis_length / max_chunk_size))
# Even chunks: ceil(axis_length / num_chunks) <= max_chunk_size.
chunk_length = int(np_ceil(axis_length / num_chunks))
return chunk_length, num_chunks
[docs]
def compute_chunked_shapes(
self,
requests: dict[str, ArrayRequest],
chunk_size: int,
) -> dict[str, Tuple[int, ...]]:
"""
Compute per-array chunked shapes based on available memory.
Parameters
----------
requests
Dictionary mapping labels to array requests.
chunk_size
Length of chunked arrays along run axis
Returns
-------
dict[str, tuple[int, ...]]
Mapping from array labels to their per-chunk shapes.
Notes
-----
Unchunkable arrays retain their original shape.
"""
chunked_shapes = {}
for key, request in requests.items():
if is_request_chunkable(request):
axis_index = request.chunk_axis_index
newshape = replace_with_chunked_size(
shape=request.shape,
axis_index=axis_index,
chunked_size=chunk_size,
)
chunked_shapes[key] = newshape
else:
chunked_shapes[key] = request.shape
return chunked_shapes
def partition_covers(
partition: Tuple[int, int], num_runs: int
) -> bool:
"""Return whether the even chunks of ``partition`` hold ``num_runs``."""
chunk_length, num_chunks = partition
if chunk_length < 1 or num_chunks < 1:
return False
return int(np_ceil(num_runs / num_chunks)) == chunk_length
def defer_instance_teardown(
memory_manager: MemoryManager,
instance_id: int,
settings: InstanceMemorySettings,
cleanups: Tuple[Callable[[], None], ...],
) -> None:
"""Record a collected client's teardown; the GC finalizer target.
See :meth:`MemoryManager.defer_teardown` for why the callback
must not run the teardown itself.
"""
memory_manager.defer_teardown(
partial(
run_instance_teardown,
memory_manager,
instance_id,
settings,
cleanups,
)
)
def run_instance_teardown(
memory_manager: MemoryManager,
instance_id: int,
settings: InstanceMemorySettings,
cleanups: Tuple[Callable[[], None], ...],
) -> None:
"""Best-effort cleanup for a collected client."""
try:
for cleanup in cleanups:
cleanup()
memory_manager.release_instance(instance_id, settings)
except Exception: # pragma: no cover - defensive at shutdown
# Keep the entry alive if cleanup could not safely finish.
settings.instance_ref = None
def get_portioned_request_size(
requests: dict[str, dict[str, ArrayRequest]],
) -> tuple[int, int]:
"""
Calculate total memory requested for the chunkable and unchunkable
portions of the request.
Chunking is performed along the run axis only.
Parameters
----------
requests
Dictionary of array requests to analyze.
Returns
-------
int, int
chunkable, unchunkable - Total bytes for arrays that can be chunked
or not, respectively, along the "run" axis.
Notes
-----
Arrays are chunkable if:
- request.unchunkable is False
- The array has a "run" axis
"""
chunkable = 0
unchunkable = 0
for reqs in requests.values():
chunkable += sum(
prod(req.shape) * req.dtype().itemsize
for req in reqs.values()
if is_request_chunkable(req)
)
unchunkable += sum(
prod(req.shape) * req.dtype().itemsize
for req in reqs.values()
if not is_request_chunkable(req)
)
return chunkable, unchunkable
def is_request_chunkable(request) -> bool:
"""
Determine if a single ArrayRequest is chunkable.
Chunking is always performed along the run axis.
Parameters
----------
request
The ArrayRequest to evaluate.
Returns
-------
bool
True if the request is chunkable, False otherwise.
Notes
-----
A request is considered chunkable if:
- request.unchunkable is False
- chunk_axis_index is not None and within bounds
- run axis has length > 1 (not a degenerate run axis)
"""
if request.unchunkable:
return False
if len(request.shape) == 0:
return False
if request.chunk_axis_index is None:
return False
if request.chunk_axis_index >= len(request.shape):
return False
if request.shape[request.chunk_axis_index] == 1:
return False
return True
def replace_with_chunked_size(
shape: Tuple[int, ...],
axis_index: int,
chunked_size: int,
) -> Tuple[int, ...]:
"""
Replace the "run" axis in shape with chunked size.
Parameters
----------
shape
Original shape of the array.
axis_index
integer index of the run axis in shape
chunked_size
Length of array after chunking along run axis
Returns
-------
tuple[int, ...]
New shape with chunked size along the "run" axis.
"""
newshape = tuple(
dim if i != axis_index else chunked_size for i, dim in enumerate(shape)
)
return newshape