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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions cuda_core/cuda/core/_memory/_pinned_memory_resource.pxd
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,5 @@ from cuda.core._memory._memory_pool cimport _MemPool

cdef class PinnedMemoryResource(_MemPool):
cdef int _numa_id
# False only for an imported pool whose node is unknown (see numa_id).
cdef bint _numa_id_known
34 changes: 29 additions & 5 deletions cuda_core/cuda/core/_memory/_pinned_memory_resource.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ class PinnedMemoryResource(_MemPool):
If the memory resource already has a different UUID.
"""
@classmethod
def from_allocation_handle(cls, alloc_handle: int | IPCAllocationHandle) -> PinnedMemoryResource:
def from_allocation_handle(cls, alloc_handle: int | IPCAllocationHandle, numa_id: int | None=None) -> PinnedMemoryResource:
"""Create a host-pinned memory resource from an allocation handle.

Construct a new `PinnedMemoryResource` instance that imports a memory
Expand All @@ -159,6 +159,18 @@ class PinnedMemoryResource(_MemPool):
The shareable handle of the host-pinned memory resource to import. If an
integer is supplied, it must represent a valid platform-specific
handle. It is the caller's responsibility to close that handle.
numa_id : int | None, optional
The host NUMA node the exporting process placed the pool on, that
is, the exporting resource's :attr:`numa_id`. Node IDs are the same
in every process on the host. The pool's node is read from the
driver when possible (a CUDA 13 build of ``cuda.core`` and a 13.2
or later driver); otherwise this value is the imported resource's
:attr:`numa_id`. Unpickling a resource passes the exporter's node
automatically if it was known. If the handle's resource is already
registered in this process with an unknown node, this value becomes
its node. If the node comes from neither the driver nor this
argument, the import succeeds but :attr:`numa_id` raises
``RuntimeError``. Must be >= 0 if given.

Returns
-------
Expand All @@ -172,6 +184,11 @@ class PinnedMemoryResource(_MemPool):
The pool's kind is checked with a CUDA 13 build of ``cuda.core``
and a 13.2 or later driver. Otherwise it is checked only when the
handle's memory resource is already registered in this process.
Also raised if ``numa_id`` is not an integer.
ValueError
If ``numa_id`` is negative or too large for a C ``int``, or
differs from the node of the pool, as reported by the driver or by
the resource already registered in this process for the handle.
"""
@property
def allocation_handle(self) -> IPCAllocationHandle:
Expand All @@ -187,10 +204,17 @@ class PinnedMemoryResource(_MemPool):
def numa_id(self) -> int:
"""The host NUMA node ID used for pool placement, or -1 for OS-managed placement.

For a resource imported with :meth:`from_allocation_handle`, this is the
pool's node only if the pool's location can be queried (a CUDA 13 build
of ``cuda.core`` and a 13.2 or later driver). Otherwise it is 0, which is
not known to be the pool's node.
For a resource imported with :meth:`from_allocation_handle`, the node
comes from the driver if the pool's location can be queried (a CUDA 13
build of ``cuda.core`` and a 13.2 or later driver), otherwise from the
``numa_id`` argument of :meth:`from_allocation_handle`, which unpickling
passes automatically if the exporter's node was known.

Raises
------
RuntimeError
If the resource was imported and none of these sources gave the
pool's node.
"""
@property
def is_device_accessible(self) -> bool:
Expand Down
104 changes: 93 additions & 11 deletions cuda_core/cuda/core/_memory/_pinned_memory_resource.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

from __future__ import annotations

cimport cython
from cuda.bindings cimport cydriver
from cuda.core._memory._buffer cimport Buffer
from cuda.core._memory._memory_pool cimport (
Expand All @@ -22,10 +23,12 @@ from cuda.core._utils.cuda_utils cimport (
check_or_create_options,
HANDLE_RETURN,
)
from libc.limits cimport INT_MAX
from libcpp.vector cimport vector

from dataclasses import dataclass
import multiprocessing
import operator
import platform # no-cython-lint
import uuid

Expand Down Expand Up @@ -198,7 +201,7 @@ cdef class PinnedMemoryResource(_MemPool):

@classmethod
def from_allocation_handle(
cls, alloc_handle: int | IPCAllocationHandle
cls, alloc_handle: int | IPCAllocationHandle, numa_id: int | None = None
) -> PinnedMemoryResource:
"""Create a host-pinned memory resource from an allocation handle.

Expand All @@ -213,6 +216,18 @@ cdef class PinnedMemoryResource(_MemPool):
The shareable handle of the host-pinned memory resource to import. If an
integer is supplied, it must represent a valid platform-specific
handle. It is the caller's responsibility to close that handle.
numa_id : int | None, optional
The host NUMA node the exporting process placed the pool on, that
is, the exporting resource's :attr:`numa_id`. Node IDs are the same
in every process on the host. The pool's node is read from the
driver when possible (a CUDA 13 build of ``cuda.core`` and a 13.2
or later driver); otherwise this value is the imported resource's
:attr:`numa_id`. Unpickling a resource passes the exporter's node
automatically if it was known. If the handle's resource is already
registered in this process with an unknown node, this value becomes
its node. If the node comes from neither the driver nor this
argument, the import succeeds but :attr:`numa_id` raises
``RuntimeError``. Must be >= 0 if given.

Returns
-------
Expand All @@ -226,16 +241,32 @@ cdef class PinnedMemoryResource(_MemPool):
The pool's kind is checked with a CUDA 13 build of ``cuda.core``
and a 13.2 or later driver. Otherwise it is checked only when the
handle's memory resource is already registered in this process.
Also raised if ``numa_id`` is not an integer.
ValueError
If ``numa_id`` is negative or too large for a C ``int``, or
differs from the node of the pool, as reported by the driver or by
the resource already registered in this process for the handle.
"""
if numa_id is not None:
# Reject a float or other non-integer instead of truncating it later.
numa_id = operator.index(numa_id)
# The node is stored as a C int once the pool is imported.
if not 0 <= numa_id <= INT_MAX:
raise ValueError(f"numa_id must be between 0 and {INT_MAX}, got {numa_id}")

# cuMemPoolImportFromShareableHandle requires CUDA to be initialized, but in
# a child process CUDA may not be initialized yet. For DeviceMemoryResource,
# this is not a concern because most likely when retrieving the device_id the
# user would have already initialized CUDA. But since PinnedMemoryResource is
# not device-specific it is unlikelt the case.
HANDLE_RETURN(cydriver.cuInit(0))

return <PinnedMemoryResource>(
_ipc.MP_from_allocation_handle(cls, alloc_handle, _PMR_init_imported))
cdef PinnedMemoryResource mr = <PinnedMemoryResource>(
_ipc.MP_from_allocation_handle(cls, alloc_handle, _PMR_init_imported, numa_id))
# The import hook does not run for a resource that is already registered,
# whether found at the start or registered by a concurrent import.
_PMR_apply_numa_id(mr, numa_id)
return mr

@property
def allocation_handle(self) -> IPCAllocationHandle:
Expand All @@ -255,14 +286,27 @@ cdef class PinnedMemoryResource(_MemPool):
return -1

@property
@cython.critical_section
def numa_id(self) -> int:
"""The host NUMA node ID used for pool placement, or -1 for OS-managed placement.

For a resource imported with :meth:`from_allocation_handle`, this is the
pool's node only if the pool's location can be queried (a CUDA 13 build
of ``cuda.core`` and a 13.2 or later driver). Otherwise it is 0, which is
not known to be the pool's node.
For a resource imported with :meth:`from_allocation_handle`, the node
comes from the driver if the pool's location can be queried (a CUDA 13
build of ``cuda.core`` and a 13.2 or later driver), otherwise from the
``numa_id`` argument of :meth:`from_allocation_handle`, which unpickling
passes automatically if the exporter's node was known.

Raises
------
RuntimeError
If the resource was imported and none of these sources gave the
pool's node.
"""
if not self._numa_id_known:
raise RuntimeError(
"The NUMA node of this imported memory pool is not known in this "
"process. Pass numa_id to PinnedMemoryResource.from_allocation_handle "
"to name the node the exporting process placed the pool on.")
return self._numa_id

@property
Expand Down Expand Up @@ -322,6 +366,7 @@ cdef inline _PMR_init(PinnedMemoryResource self, options):
loc_type = cydriver.CUmemLocationType.CU_MEM_LOCATION_TYPE_HOST

self._numa_id = numa_id
self._numa_id_known = True

if opts is None:
MP_init_current_pool(
Expand Down Expand Up @@ -365,23 +410,60 @@ cdef inline int _PMR_grant_device_access(
return 0


cdef int _PMR_init_imported(_MemPool mr, object unused) except? -1:
cdef inline int _PMR_apply_numa_id(PinnedMemoryResource self, object numa_id) except? -1:
# A node the caller passed must agree with a node that is known. A resource
# whose node is unknown, such as one registered by an earlier import that
# was given no node, takes the caller's node.
# Concurrent imports of one handle share this resource, so on a free-threaded
# build the check and the write are one step. Otherwise two imports with
# different nodes could both find the node unknown and both succeed.
cdef int node
if numa_id is None:
return 0
node = numa_id
with cython.critical_section(self):
if not self._numa_id_known:
self._numa_id = node
self._numa_id_known = True
elif self._numa_id != node:
raise ValueError(
f"numa_id {node} does not match the NUMA node of the memory pool, "
f"which is {self._numa_id}")
return 0


cdef int _PMR_init_imported(_MemPool mr, object numa_id) except? -1:
cdef PinnedMemoryResource self = <PinnedMemoryResource>mr
cdef cydriver.CUmemLocation loc
# IPC-enabled pinned pools created by cuda.core are always placed on a host
# NUMA node. Without a location query (a CUDA 12 build or a driver before
# 13.2), the pool's kind is not checked and numa_id keeps its default.
# 13.2), the pool's kind is not checked and the node is the one the caller
# passed, if any. Otherwise it is unknown and the numa_id property raises.
cdef bint host_numa = True
if _ipc.MP_check_import_location(self, True, &loc):
host_numa = loc.type == cydriver.CUmemLocationType.CU_MEM_LOCATION_TYPE_HOST_NUMA
self._numa_id = loc.id if host_numa else -1
self._numa_id_known = True
_PMR_apply_numa_id(self, numa_id)
elif numa_id is not None:
self._numa_id = numa_id
self._numa_id_known = True
return _PMR_grant_device_access(self, host_numa, True)


def _deep_reduce_pinned_memory_resource(mr: object) -> tuple[object, ...]:
check_multiprocessing_start_method()
alloc_handle = mr.allocation_handle
return mr.from_allocation_handle, (alloc_handle,)
cdef PinnedMemoryResource pmr = <PinnedMemoryResource>mr
alloc_handle = pmr.allocation_handle
# NUMA node IDs are the same in every process on the host, so the node needs
# no translation as a device ordinal does. An unknown node is not sent, so
# that the importer does not mistake a placeholder for the pool's node, and
# neither is -1, which from_allocation_handle rejects.
numa_id = None
with cython.critical_section(pmr):
if pmr._numa_id_known and pmr._numa_id >= 0:
numa_id = pmr._numa_id
return pmr.from_allocation_handle, (alloc_handle, numa_id)


multiprocessing.reduction.register(PinnedMemoryResource, _deep_reduce_pinned_memory_resource)
14 changes: 14 additions & 0 deletions cuda_core/docs/source/release/1.4.0-notes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -59,3 +59,17 @@ Fixes and enhancements
later driver; with a CUDA 12 build or an older driver, imports behave as
before.
(`#3502 <https://github.com/NVIDIA/cuda-python/issues/3502>`__)

- An imported :class:`PinnedMemoryResource` reports the exporting resource's
NUMA node as ``numa_id`` also with a CUDA 12 build of ``cuda.core`` or a
driver before 13.2, where the pool's node cannot be queried. Unpickling a
resource now carries the node, and
:meth:`PinnedMemoryResource.from_allocation_handle` accepts an optional
``numa_id`` argument for a raw allocation handle. If the handle's resource is
already registered in the process with an unknown node, the argument becomes
its node. ``from_allocation_handle`` raises ``TypeError`` for a ``numa_id``
that is not an integer, and ``ValueError`` for a negative or too large one
or one that differs from the pool's known node. When the node can be neither queried nor taken from the
argument, :attr:`PinnedMemoryResource.numa_id` now raises ``RuntimeError``
instead of returning 0, which was not known to be the pool's node.
(`#3508 <https://github.com/NVIDIA/cuda-python/issues/3508>`__)
6 changes: 6 additions & 0 deletions cuda_core/tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -577,6 +577,12 @@ def ipc_pool_memory_resource(request, ipc_device):
yield from _ipc_memory_resource(request.param, ipc_device)


@pytest.fixture
def ipc_pinned_memory_resource(ipc_device):
"""Provides an IPC-enabled pinned memory pool, or skips."""
yield from _ipc_memory_resource("pinned", ipc_device)


@pytest.fixture(params=[_DEVICE_MR, _VIRTUAL_MR])
def ipc_memory_resource_factory(request, ipc_device):
"""Provides a callable that creates fresh IPC-enabled resources of one kind; all are closed at teardown."""
Expand Down
11 changes: 7 additions & 4 deletions cuda_core/tests/helpers/memory.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,15 +66,18 @@ def is_pool_resource(mr):
return isinstance(mr, (DeviceMemoryResource, PinnedMemoryResource))


def import_pool_resource(cls, device, alloc_handle):
def import_pool_resource(cls, device, alloc_handle, numa_id=None):
"""Import the pool shared by ``alloc_handle`` as ``cls``, the class of the exporting resource.

The class must match the exporter: importing a pinned pool as a
``DeviceMemoryResource`` (or the reverse) raises ``TypeError`` (#3502).
``numa_id`` is passed to ``PinnedMemoryResource.from_allocation_handle``
and must be ``None`` for a ``DeviceMemoryResource``.
"""
if cls is PinnedMemoryResource:
return PinnedMemoryResource.from_allocation_handle(alloc_handle)
return PinnedMemoryResource.from_allocation_handle(alloc_handle, numa_id=numa_id)
assert cls is DeviceMemoryResource, cls
assert numa_id is None, numa_id
return DeviceMemoryResource.from_allocation_handle(device, alloc_handle)


Expand Down Expand Up @@ -103,13 +106,13 @@ def drain_on_exit(stack, synchronizable):
stack.callback(synchronizable.sync)


def enter_imported_pool(stack, cls, device, alloc_handle):
def enter_imported_pool(stack, cls, device, alloc_handle, numa_id=None):
"""Import the pool like :func:`import_pool_resource`, and register it to close on ``stack``.

``stack`` is a :class:`contextlib.ExitStack`. A pool resource is not a
context manager, so it is entered through :func:`contextlib.closing`.
"""
return stack.enter_context(contextlib.closing(import_pool_resource(cls, device, alloc_handle)))
return stack.enter_context(contextlib.closing(import_pool_resource(cls, device, alloc_handle, numa_id)))


def pool_access_flags(mr, device):
Expand Down
Loading
Loading