From 673d500f393e3a585c645803fdf55b1a814fa810 Mon Sep 17 00:00:00 2001 From: Ralf Juengling Date: Sat, 21 Nov 2026 07:14:56 -0800 Subject: [PATCH 1/8] fix(cuda.core): report the exporter's NUMA node on imported pinned pools An imported PinnedMemoryResource reported numa_id 0 whenever the driver could not report the pool's location (a CUDA 12 build or a driver before 13.2). Unpickling a resource now carries the exporter's node, and PinnedMemoryResource.from_allocation_handle accepts an optional numa_id for a raw allocation handle. An import whose node is unknown still reports 0 and does not pass it on when pickled. from_allocation_handle raises ValueError for a negative numa_id, and for one that differs from the pool's known node, whether the driver reported it or the resource was already registered in the process. Closes #3508. Signed-off-by: Ralf Juengling --- .../core/_memory/_pinned_memory_resource.pxd | 2 + .../core/_memory/_pinned_memory_resource.pyi | 22 ++- .../core/_memory/_pinned_memory_resource.pyx | 61 ++++++-- cuda_core/docs/source/release/1.4.0-notes.rst | 11 ++ .../tests/memory_ipc/test_ipc_pool_kind.py | 133 ++++++++++++++++++ 5 files changed, 215 insertions(+), 14 deletions(-) diff --git a/cuda_core/cuda/core/_memory/_pinned_memory_resource.pxd b/cuda_core/cuda/core/_memory/_pinned_memory_resource.pxd index 41336d4f61ad..a09c2fb46ed9 100644 --- a/cuda_core/cuda/core/_memory/_pinned_memory_resource.pxd +++ b/cuda_core/cuda/core/_memory/_pinned_memory_resource.pxd @@ -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 diff --git a/cuda_core/cuda/core/_memory/_pinned_memory_resource.pyi b/cuda_core/cuda/core/_memory/_pinned_memory_resource.pyi index 9f9a7204fa81..64e8f68638bf 100644 --- a/cuda_core/cuda/core/_memory/_pinned_memory_resource.pyi +++ b/cuda_core/cuda/core/_memory/_pinned_memory_resource.pyi @@ -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 @@ -159,6 +159,14 @@ 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. Must be >= 0 if given. Returns ------- @@ -172,6 +180,10 @@ 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. + ValueError + If ``numa_id`` is negative, 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: @@ -188,9 +200,11 @@ class PinnedMemoryResource(_MemPool): """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. + pool's node if the pool's location can be queried (a CUDA 13 build of + ``cuda.core`` and a 13.2 or later driver), if the caller passed + ``numa_id`` to :meth:`from_allocation_handle`, or if the resource was + unpickled from a resource whose node was known. Otherwise it is 0, which + is not known to be the pool's node. """ @property def is_device_accessible(self) -> bool: diff --git a/cuda_core/cuda/core/_memory/_pinned_memory_resource.pyx b/cuda_core/cuda/core/_memory/_pinned_memory_resource.pyx index 965f4df59a4e..a6ebf2f981b5 100644 --- a/cuda_core/cuda/core/_memory/_pinned_memory_resource.pyx +++ b/cuda_core/cuda/core/_memory/_pinned_memory_resource.pyx @@ -198,7 +198,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. @@ -213,6 +213,14 @@ 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. Must be >= 0 if given. Returns ------- @@ -226,7 +234,14 @@ 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. + ValueError + If ``numa_id`` is negative, 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 and numa_id < 0: + raise ValueError(f"numa_id must be >= 0, 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 @@ -234,8 +249,12 @@ cdef class PinnedMemoryResource(_MemPool): # not device-specific it is unlikelt the case. HANDLE_RETURN(cydriver.cuInit(0)) - return ( - _ipc.MP_from_allocation_handle(cls, alloc_handle, _PMR_init_imported)) + cdef PinnedMemoryResource mr = ( + _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_check_numa_id(mr, numa_id) + return mr @property def allocation_handle(self) -> IPCAllocationHandle: @@ -259,9 +278,11 @@ cdef class PinnedMemoryResource(_MemPool): """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. + pool's node if the pool's location can be queried (a CUDA 13 build of + ``cuda.core`` and a 13.2 or later driver), if the caller passed + ``numa_id`` to :meth:`from_allocation_handle`, or if the resource was + unpickled from a resource whose node was known. Otherwise it is 0, which + is not known to be the pool's node. """ return self._numa_id @@ -322,6 +343,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( @@ -365,23 +387,42 @@ cdef inline int _PMR_grant_device_access( return 0 -cdef int _PMR_init_imported(_MemPool mr, object unused) except? -1: +cdef inline int _PMR_check_numa_id(PinnedMemoryResource self, object numa_id) except? -1: + # A node the caller passed must agree with a node that is known. + if numa_id is not None and self._numa_id_known and self._numa_id != numa_id: + raise ValueError( + f"numa_id {numa_id} 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 = 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 numa_id keeps its default. 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_check_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 = 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 the default 0 for the pool's node. + return pmr.from_allocation_handle, (alloc_handle, pmr._numa_id if pmr._numa_id_known else None) multiprocessing.reduction.register(PinnedMemoryResource, _deep_reduce_pinned_memory_resource) diff --git a/cuda_core/docs/source/release/1.4.0-notes.rst b/cuda_core/docs/source/release/1.4.0-notes.rst index 1be489a39591..b6850fb85c23 100644 --- a/cuda_core/docs/source/release/1.4.0-notes.rst +++ b/cuda_core/docs/source/release/1.4.0-notes.rst @@ -59,3 +59,14 @@ Fixes and enhancements later driver; with a CUDA 12 build or an older driver, imports behave as before. (`#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. Without it, an import that + cannot query the node still reports 0, which is not known to be the pool's + node. ``from_allocation_handle`` raises ``ValueError`` for a negative + ``numa_id`` or one that differs from the pool's known node. + (`#3508 `__) diff --git a/cuda_core/tests/memory_ipc/test_ipc_pool_kind.py b/cuda_core/tests/memory_ipc/test_ipc_pool_kind.py index b7edc0192265..ce1ff4ea2106 100644 --- a/cuda_core/tests/memory_ipc/test_ipc_pool_kind.py +++ b/cuda_core/tests/memory_ipc/test_ipc_pool_kind.py @@ -38,6 +38,7 @@ ) from cuda.core._memory import _memory_pool from cuda.core._memory._buffer import _live_owned_mempool_count +from cuda.core._memory._pinned_memory_resource import _deep_reduce_pinned_memory_resource NBYTES = 64 @@ -131,6 +132,93 @@ def child_imported_numa_id(alloc_handle, numa_id): mr.close() +def child_unpickled_numa_id(mr, numa_id): + # The resource was unpickled while the child's arguments were loaded. + assert mr.numa_id == numa_id + mr.close() + + +def _without_location_query(): + # Stand in for a 13.0 or 13.1 driver (see child_import_without_location_query). + _memory_pool.driver_version = lambda: (13, 1, 0) + + +# A node that the tests cannot confuse with the default of 0. Without a location +# query nothing checks it against the pool. +CLAIMED_NUMA_ID = 7 + + +def child_import_with_numa_id_without_location_query(alloc_handle): + _without_location_query() + Device().set_current() + + # A raw file descriptor carries no UUID, so each import is a separate resource. + omitted = PinnedMemoryResource.from_allocation_handle(int(alloc_handle)) + assert omitted.numa_id == 0 + given = PinnedMemoryResource.from_allocation_handle(int(alloc_handle), numa_id=CLAIMED_NUMA_ID) + assert given.numa_id == CLAIMED_NUMA_ID + given.close() + omitted.close() + + +def child_import_reduced_args_without_location_query(reduced_args): + _without_location_query() + Device().set_current() + mr = PinnedMemoryResource.from_allocation_handle(*reduced_args) + assert mr.numa_id == reduced_args[1] + mr.close() + + +def child_reduce_imported_resource(alloc_handle): + _without_location_query() + Device().set_current() + + # The node of this import is unknown, so a third process must not be told 0. + unknown = PinnedMemoryResource.from_allocation_handle(int(alloc_handle)) + assert unknown.numa_id == 0 + assert _deep_reduce_pinned_memory_resource(unknown)[1][1] is None + + known = PinnedMemoryResource.from_allocation_handle(int(alloc_handle), numa_id=CLAIMED_NUMA_ID) + assert _deep_reduce_pinned_memory_resource(known)[1][1] == CLAIMED_NUMA_ID + known.close() + unknown.close() + + +def child_registered_import_rejects_conflicting_numa_id(alloc_handle): + _without_location_query() + Device().set_current() + baseline = _live_owned_mempool_count() + + mr = PinnedMemoryResource.from_allocation_handle(alloc_handle, numa_id=CLAIMED_NUMA_ID) + # The handle's UUID is now registered, so the resource is returned as is. + assert PinnedMemoryResource.from_allocation_handle(alloc_handle, numa_id=CLAIMED_NUMA_ID) is mr + with pytest.raises(ValueError, match="numa_id"): + PinnedMemoryResource.from_allocation_handle(alloc_handle, numa_id=CLAIMED_NUMA_ID + 1) + assert PinnedMemoryResource.from_allocation_handle(alloc_handle) is mr + assert mr.numa_id == CLAIMED_NUMA_ID + + mr.close() + assert _live_owned_mempool_count() == baseline + + +def child_numa_id_is_checked_against_driver(alloc_handle): + Device().set_current() + baseline = _live_owned_mempool_count() + + mr = PinnedMemoryResource.from_allocation_handle(int(alloc_handle)) + node = mr.numa_id + # Releasing the rejected import cannot raise; a failed cuMemPoolDestroy + # surfaces only as a CUDAWarning. + with assert_no_cuda_warning(), pytest.raises(ValueError, match="numa_id"): + PinnedMemoryResource.from_allocation_handle(int(alloc_handle), numa_id=node + 1) + + matching = PinnedMemoryResource.from_allocation_handle(int(alloc_handle), numa_id=node) + assert matching.numa_id == node + matching.close() + mr.close() + assert _live_owned_mempool_count() == baseline + + def child_matching_import(mr_type, alloc_handle, descriptor): device = Device() device.set_current() @@ -180,6 +268,15 @@ def _set_start_method(self): with contextlib.suppress(RuntimeError): mp.set_start_method("spawn", force=True) + @pytest.fixture + def pinned_ipc_resource(self, ipc_device): + skip_if_host_numa_pinned_memory_unsupported(ipc_device) + ipc_device.set_current() + mr = PinnedMemoryResource(PinnedMemoryResourceOptions(max_size=POOL_SIZE, ipc_enabled=True)) + yield mr + mr.close() + ipc_device.sync() + @pytest.fixture def pool_resource(self, ipc_memory_resource): if not is_pool_resource(ipc_memory_resource): @@ -259,5 +356,41 @@ def test_imported_pinned_resource_reports_numa_id(self, ipc_device): try: assert mr.numa_id == numa_id run_child(child_imported_numa_id, mr.allocation_handle, numa_id) + # Unpickling the resource is the other import path. + run_child(child_unpickled_numa_id, mr, numa_id) finally: mr.close() + + @pytest.mark.agent_authored(model="claude-sonnet-5-5") + def test_numa_id_is_checked_against_driver(self, pinned_ipc_resource): + run_child(child_numa_id_is_checked_against_driver, pinned_ipc_resource.allocation_handle) + + +class TestPinnedImportNumaId(_IpcPoolFixtures): + """Without a location query, an imported pinned pool's node comes from the caller or the pickle (#3508).""" + + @pytest.mark.agent_authored(model="claude-sonnet-5-5") + def test_import_uses_given_numa_id(self, pinned_ipc_resource): + run_child(child_import_with_numa_id_without_location_query, pinned_ipc_resource.allocation_handle) + + @pytest.mark.agent_authored(model="claude-sonnet-5-5") + def test_pickle_carries_numa_id(self, pinned_ipc_resource): + _, reduced_args = _deep_reduce_pinned_memory_resource(pinned_ipc_resource) + assert reduced_args[0] is pinned_ipc_resource.allocation_handle + assert reduced_args[1] == pinned_ipc_resource.numa_id + run_child(child_import_reduced_args_without_location_query, reduced_args) + + @pytest.mark.agent_authored(model="claude-sonnet-5-5") + def test_pickle_omits_unknown_numa_id(self, pinned_ipc_resource): + run_child(child_reduce_imported_resource, pinned_ipc_resource.allocation_handle) + + @pytest.mark.agent_authored(model="claude-sonnet-5-5") + def test_registered_import_rejects_conflicting_numa_id(self, pinned_ipc_resource): + run_child(child_registered_import_rejects_conflicting_numa_id, pinned_ipc_resource.allocation_handle) + + @pytest.mark.agent_authored(model="claude-sonnet-5-5") + @pytest.mark.parametrize("numa_id", [-1, -5]) + def test_negative_numa_id_raises(self, numa_id): + # Rejected before the handle is used or CUDA is initialized. + with pytest.raises(ValueError, match="numa_id"): + PinnedMemoryResource.from_allocation_handle(0, numa_id=numa_id) From dcde304578aafddb5ff3698a9bca4653e8866599 Mon Sep 17 00:00:00 2001 From: Ralf Juengling Date: Wed, 25 Nov 2026 16:23:27 -0800 Subject: [PATCH 2/8] fix(cuda.core): raise from PinnedMemoryResource.numa_id when the node is unknown An imported pool whose node neither the driver nor the caller reports no longer reports 0. The numa_id property raises RuntimeError instead, as #3508 now specifies. --- .../core/_memory/_pinned_memory_resource.pyi | 21 ++++++++----- .../core/_memory/_pinned_memory_resource.pyx | 30 +++++++++++++------ cuda_core/docs/source/release/1.4.0-notes.rst | 9 +++--- .../tests/memory_ipc/test_ipc_pool_kind.py | 14 +++++---- 4 files changed, 48 insertions(+), 26 deletions(-) diff --git a/cuda_core/cuda/core/_memory/_pinned_memory_resource.pyi b/cuda_core/cuda/core/_memory/_pinned_memory_resource.pyi index 64e8f68638bf..6ca2d3cc0066 100644 --- a/cuda_core/cuda/core/_memory/_pinned_memory_resource.pyi +++ b/cuda_core/cuda/core/_memory/_pinned_memory_resource.pyi @@ -166,7 +166,9 @@ class PinnedMemoryResource(_MemPool): 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. Must be >= 0 if given. + automatically if it was known. 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 ------- @@ -199,12 +201,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 if the pool's location can be queried (a CUDA 13 build of - ``cuda.core`` and a 13.2 or later driver), if the caller passed - ``numa_id`` to :meth:`from_allocation_handle`, or if the resource was - unpickled from a resource whose node was known. 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: diff --git a/cuda_core/cuda/core/_memory/_pinned_memory_resource.pyx b/cuda_core/cuda/core/_memory/_pinned_memory_resource.pyx index a6ebf2f981b5..d478aba19355 100644 --- a/cuda_core/cuda/core/_memory/_pinned_memory_resource.pyx +++ b/cuda_core/cuda/core/_memory/_pinned_memory_resource.pyx @@ -220,7 +220,9 @@ cdef class PinnedMemoryResource(_MemPool): 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. Must be >= 0 if given. + automatically if it was known. 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 ------- @@ -277,13 +279,23 @@ cdef 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 if the pool's location can be queried (a CUDA 13 build of - ``cuda.core`` and a 13.2 or later driver), if the caller passed - ``numa_id`` to :meth:`from_allocation_handle`, or if the resource was - unpickled from a resource whose node was known. 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 @@ -402,7 +414,7 @@ cdef int _PMR_init_imported(_MemPool mr, object numa_id) except? -1: # 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 the node is the one the caller - # passed, if any. Otherwise it is unknown and numa_id keeps its default. + # 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 @@ -421,7 +433,7 @@ def _deep_reduce_pinned_memory_resource(mr: object) -> tuple[object, ...]: 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 the default 0 for the pool's node. + # that the importer does not mistake a placeholder for the pool's node. return pmr.from_allocation_handle, (alloc_handle, pmr._numa_id if pmr._numa_id_known else None) diff --git a/cuda_core/docs/source/release/1.4.0-notes.rst b/cuda_core/docs/source/release/1.4.0-notes.rst index b6850fb85c23..543f057f63ba 100644 --- a/cuda_core/docs/source/release/1.4.0-notes.rst +++ b/cuda_core/docs/source/release/1.4.0-notes.rst @@ -65,8 +65,9 @@ Fixes and enhancements 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. Without it, an import that - cannot query the node still reports 0, which is not known to be the pool's - node. ``from_allocation_handle`` raises ``ValueError`` for a negative - ``numa_id`` or one that differs from the pool's known node. + ``numa_id`` argument for a raw allocation handle. ``from_allocation_handle`` + raises ``ValueError`` for a negative ``numa_id`` 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 `__) diff --git a/cuda_core/tests/memory_ipc/test_ipc_pool_kind.py b/cuda_core/tests/memory_ipc/test_ipc_pool_kind.py index ce1ff4ea2106..8b3cd5c1aa34 100644 --- a/cuda_core/tests/memory_ipc/test_ipc_pool_kind.py +++ b/cuda_core/tests/memory_ipc/test_ipc_pool_kind.py @@ -143,8 +143,9 @@ def _without_location_query(): _memory_pool.driver_version = lambda: (13, 1, 0) -# A node that the tests cannot confuse with the default of 0. Without a location -# query nothing checks it against the pool. +# A node that the tests cannot confuse with the pool's actual node or with +# Cython's zero initialization. Without a location query nothing checks it +# against the pool. CLAIMED_NUMA_ID = 7 @@ -154,7 +155,8 @@ def child_import_with_numa_id_without_location_query(alloc_handle): # A raw file descriptor carries no UUID, so each import is a separate resource. omitted = PinnedMemoryResource.from_allocation_handle(int(alloc_handle)) - assert omitted.numa_id == 0 + with pytest.raises(RuntimeError, match="NUMA node .* is not known"): + _ = omitted.numa_id given = PinnedMemoryResource.from_allocation_handle(int(alloc_handle), numa_id=CLAIMED_NUMA_ID) assert given.numa_id == CLAIMED_NUMA_ID given.close() @@ -173,9 +175,8 @@ def child_reduce_imported_resource(alloc_handle): _without_location_query() Device().set_current() - # The node of this import is unknown, so a third process must not be told 0. + # The node of this import is unknown, so a third process must not be told a node. unknown = PinnedMemoryResource.from_allocation_handle(int(alloc_handle)) - assert unknown.numa_id == 0 assert _deep_reduce_pinned_memory_resource(unknown)[1][1] is None known = PinnedMemoryResource.from_allocation_handle(int(alloc_handle), numa_id=CLAIMED_NUMA_ID) @@ -256,7 +257,8 @@ def child_import_without_location_query(mr_type, alloc_handle, descriptor): mr = enter_imported_pool(stack, mr_type, device, int(alloc_handle)) if mr_type is PinnedMemoryResource: # Without the location query the pool's node is unknown (see numa_id). - assert mr.numa_id == 0 + with pytest.raises(RuntimeError, match="NUMA node .* is not known"): + _ = mr.numa_id buffer = stack.enter_context(Buffer.from_ipc_descriptor(mr, descriptor, stream=stream)) buffer.fill(7, stream=stream) From c90dcf7f9de6a901b14854858ca6e8238e71521c Mon Sep 17 00:00:00 2001 From: Ralf Juengling Date: Wed, 25 Nov 2026 16:29:14 -0800 Subject: [PATCH 3/8] test(cuda.core): use the shared import helpers in the pinned numa_id tests Close imported resources through an ExitStack, as the other children in test_ipc_pool_kind.py do, by letting import_pool_resource and enter_imported_pool pass numa_id. Reuse _without_location_query in child_import_without_location_query, and explain why the pickle tests send the reducer's output instead of the resource. --- cuda_core/tests/helpers/memory.py | 11 +- .../tests/memory_ipc/test_ipc_pool_kind.py | 106 +++++++++--------- 2 files changed, 63 insertions(+), 54 deletions(-) diff --git a/cuda_core/tests/helpers/memory.py b/cuda_core/tests/helpers/memory.py index 8f12e5712e89..7b1cf4fe7b76 100644 --- a/cuda_core/tests/helpers/memory.py +++ b/cuda_core/tests/helpers/memory.py @@ -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) @@ -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): diff --git a/cuda_core/tests/memory_ipc/test_ipc_pool_kind.py b/cuda_core/tests/memory_ipc/test_ipc_pool_kind.py index 8b3cd5c1aa34..d92b65bb1078 100644 --- a/cuda_core/tests/memory_ipc/test_ipc_pool_kind.py +++ b/cuda_core/tests/memory_ipc/test_ipc_pool_kind.py @@ -134,12 +134,15 @@ def child_imported_numa_id(alloc_handle, numa_id): def child_unpickled_numa_id(mr, numa_id): # The resource was unpickled while the child's arguments were loaded. - assert mr.numa_id == numa_id - mr.close() + with contextlib.closing(mr): + assert mr.numa_id == numa_id def _without_location_query(): - # Stand in for a 13.0 or 13.1 driver (see child_import_without_location_query). + # Stand in for a 13.0 or 13.1 driver, as test_program_compile_cache.py does + # for _program: MP_location_query_available reads driver_version from the + # _memory_pool module on every import. The monkeypatch fixture cannot reach a + # spawned child, and this process exits after the test. _memory_pool.driver_version = lambda: (13, 1, 0) @@ -151,72 +154,76 @@ def _without_location_query(): def child_import_with_numa_id_without_location_query(alloc_handle): _without_location_query() - Device().set_current() + device = Device() + device.set_current() # A raw file descriptor carries no UUID, so each import is a separate resource. - omitted = PinnedMemoryResource.from_allocation_handle(int(alloc_handle)) - with pytest.raises(RuntimeError, match="NUMA node .* is not known"): - _ = omitted.numa_id - given = PinnedMemoryResource.from_allocation_handle(int(alloc_handle), numa_id=CLAIMED_NUMA_ID) - assert given.numa_id == CLAIMED_NUMA_ID - given.close() - omitted.close() + with contextlib.ExitStack() as stack: + omitted = enter_imported_pool(stack, PinnedMemoryResource, device, int(alloc_handle)) + with pytest.raises(RuntimeError, match="NUMA node .* is not known"): + _ = omitted.numa_id + given = enter_imported_pool(stack, PinnedMemoryResource, device, int(alloc_handle), CLAIMED_NUMA_ID) + assert given.numa_id == CLAIMED_NUMA_ID def child_import_reduced_args_without_location_query(reduced_args): _without_location_query() - Device().set_current() - mr = PinnedMemoryResource.from_allocation_handle(*reduced_args) - assert mr.numa_id == reduced_args[1] - mr.close() + device = Device() + device.set_current() + alloc_handle, numa_id = reduced_args + with contextlib.ExitStack() as stack: + mr = enter_imported_pool(stack, PinnedMemoryResource, device, alloc_handle, numa_id) + assert mr.numa_id == numa_id def child_reduce_imported_resource(alloc_handle): _without_location_query() - Device().set_current() + device = Device() + device.set_current() - # The node of this import is unknown, so a third process must not be told a node. - unknown = PinnedMemoryResource.from_allocation_handle(int(alloc_handle)) - assert _deep_reduce_pinned_memory_resource(unknown)[1][1] is None + # A third process would have to patch driver_version before unpickling, as + # in test_pickle_carries_numa_id, so the reducer's output is checked here. + with contextlib.ExitStack() as stack: + # The node of this import is unknown, so a third process must not be told a node. + unknown = enter_imported_pool(stack, PinnedMemoryResource, device, int(alloc_handle)) + assert _deep_reduce_pinned_memory_resource(unknown)[1][1] is None - known = PinnedMemoryResource.from_allocation_handle(int(alloc_handle), numa_id=CLAIMED_NUMA_ID) - assert _deep_reduce_pinned_memory_resource(known)[1][1] == CLAIMED_NUMA_ID - known.close() - unknown.close() + known = enter_imported_pool(stack, PinnedMemoryResource, device, int(alloc_handle), CLAIMED_NUMA_ID) + assert _deep_reduce_pinned_memory_resource(known)[1][1] == CLAIMED_NUMA_ID def child_registered_import_rejects_conflicting_numa_id(alloc_handle): _without_location_query() - Device().set_current() + device = Device() + device.set_current() baseline = _live_owned_mempool_count() - mr = PinnedMemoryResource.from_allocation_handle(alloc_handle, numa_id=CLAIMED_NUMA_ID) - # The handle's UUID is now registered, so the resource is returned as is. - assert PinnedMemoryResource.from_allocation_handle(alloc_handle, numa_id=CLAIMED_NUMA_ID) is mr - with pytest.raises(ValueError, match="numa_id"): - PinnedMemoryResource.from_allocation_handle(alloc_handle, numa_id=CLAIMED_NUMA_ID + 1) - assert PinnedMemoryResource.from_allocation_handle(alloc_handle) is mr - assert mr.numa_id == CLAIMED_NUMA_ID - - mr.close() + with contextlib.ExitStack() as stack: + mr = enter_imported_pool(stack, PinnedMemoryResource, device, alloc_handle, CLAIMED_NUMA_ID) + # The handle's UUID is now registered, so the resource is returned as is. + assert PinnedMemoryResource.from_allocation_handle(alloc_handle, numa_id=CLAIMED_NUMA_ID) is mr + with pytest.raises(ValueError, match="numa_id"): + PinnedMemoryResource.from_allocation_handle(alloc_handle, numa_id=CLAIMED_NUMA_ID + 1) + assert PinnedMemoryResource.from_allocation_handle(alloc_handle) is mr + assert mr.numa_id == CLAIMED_NUMA_ID assert _live_owned_mempool_count() == baseline def child_numa_id_is_checked_against_driver(alloc_handle): - Device().set_current() + device = Device() + device.set_current() baseline = _live_owned_mempool_count() - mr = PinnedMemoryResource.from_allocation_handle(int(alloc_handle)) - node = mr.numa_id - # Releasing the rejected import cannot raise; a failed cuMemPoolDestroy - # surfaces only as a CUDAWarning. - with assert_no_cuda_warning(), pytest.raises(ValueError, match="numa_id"): - PinnedMemoryResource.from_allocation_handle(int(alloc_handle), numa_id=node + 1) - - matching = PinnedMemoryResource.from_allocation_handle(int(alloc_handle), numa_id=node) - assert matching.numa_id == node - matching.close() - mr.close() + with contextlib.ExitStack() as stack: + mr = enter_imported_pool(stack, PinnedMemoryResource, device, int(alloc_handle)) + node = mr.numa_id + # Releasing the rejected import cannot raise; a failed cuMemPoolDestroy + # surfaces only as a CUDAWarning. + with assert_no_cuda_warning(), pytest.raises(ValueError, match="numa_id"): + PinnedMemoryResource.from_allocation_handle(int(alloc_handle), numa_id=node + 1) + + matching = enter_imported_pool(stack, PinnedMemoryResource, device, int(alloc_handle), node) + assert matching.numa_id == node assert _live_owned_mempool_count() == baseline @@ -238,11 +245,7 @@ def child_matching_import(mr_type, alloc_handle, descriptor): def child_import_without_location_query(mr_type, alloc_handle, descriptor): - # Stand in for a 13.0 or 13.1 driver, as test_program_compile_cache.py does - # for _program: MP_location_query_available reads driver_version from the - # _memory_pool module on every import. The monkeypatch fixture cannot reach a - # spawned child, and this process exits after the test. - _memory_pool.driver_version = lambda: (13, 1, 0) + _without_location_query() device = Device() device.set_current() stream = device.default_stream @@ -377,6 +380,9 @@ def test_import_uses_given_numa_id(self, pinned_ipc_resource): @pytest.mark.agent_authored(model="claude-sonnet-5-5") def test_pickle_carries_numa_id(self, pinned_ipc_resource): + # The child must patch driver_version before it imports the pool, but + # run_child unpickles a resource argument before the child runs. So the + # reducer's arguments are sent, and the child imports from them. _, reduced_args = _deep_reduce_pinned_memory_resource(pinned_ipc_resource) assert reduced_args[0] is pinned_ipc_resource.allocation_handle assert reduced_args[1] == pinned_ipc_resource.numa_id From a2f7a7bfa0dfebd72b09fe3861a210808b991904 Mon Sep 17 00:00:00 2001 From: Ralf Juengling Date: Wed, 25 Nov 2026 16:30:55 -0800 Subject: [PATCH 4/8] test(cuda.core): merge overlapping pinned numa_id tests Cover the reducer output and the import from it in one pickle test, drop the unknown-node assertion that test_import_uses_given_numa_id already makes, and test a single negative numa_id. --- .../tests/memory_ipc/test_ipc_pool_kind.py | 32 ++++++------------- 1 file changed, 9 insertions(+), 23 deletions(-) diff --git a/cuda_core/tests/memory_ipc/test_ipc_pool_kind.py b/cuda_core/tests/memory_ipc/test_ipc_pool_kind.py index d92b65bb1078..b925bbfd8dea 100644 --- a/cuda_core/tests/memory_ipc/test_ipc_pool_kind.py +++ b/cuda_core/tests/memory_ipc/test_ipc_pool_kind.py @@ -166,24 +166,19 @@ def child_import_with_numa_id_without_location_query(alloc_handle): assert given.numa_id == CLAIMED_NUMA_ID -def child_import_reduced_args_without_location_query(reduced_args): +def child_pickle_numa_id(reduced_args): _without_location_query() device = Device() device.set_current() alloc_handle, numa_id = reduced_args + with contextlib.ExitStack() as stack: + # Importing from the exporter's reducer output yields the exporter's node. mr = enter_imported_pool(stack, PinnedMemoryResource, device, alloc_handle, numa_id) assert mr.numa_id == numa_id - -def child_reduce_imported_resource(alloc_handle): - _without_location_query() - device = Device() - device.set_current() - - # A third process would have to patch driver_version before unpickling, as - # in test_pickle_carries_numa_id, so the reducer's output is checked here. - with contextlib.ExitStack() as stack: + # A third process would have to patch driver_version before unpickling, as + # this test does, so the reducer's output is checked here. # The node of this import is unknown, so a third process must not be told a node. unknown = enter_imported_pool(stack, PinnedMemoryResource, device, int(alloc_handle)) assert _deep_reduce_pinned_memory_resource(unknown)[1][1] is None @@ -258,10 +253,6 @@ def child_import_without_location_query(mr_type, alloc_handle, descriptor): with contextlib.ExitStack() as stack: drain_on_exit(stack, stream) mr = enter_imported_pool(stack, mr_type, device, int(alloc_handle)) - if mr_type is PinnedMemoryResource: - # Without the location query the pool's node is unknown (see numa_id). - with pytest.raises(RuntimeError, match="NUMA node .* is not known"): - _ = mr.numa_id buffer = stack.enter_context(Buffer.from_ipc_descriptor(mr, descriptor, stream=stream)) buffer.fill(7, stream=stream) @@ -379,26 +370,21 @@ def test_import_uses_given_numa_id(self, pinned_ipc_resource): run_child(child_import_with_numa_id_without_location_query, pinned_ipc_resource.allocation_handle) @pytest.mark.agent_authored(model="claude-sonnet-5-5") - def test_pickle_carries_numa_id(self, pinned_ipc_resource): + def test_pickle_numa_id(self, pinned_ipc_resource): # The child must patch driver_version before it imports the pool, but # run_child unpickles a resource argument before the child runs. So the # reducer's arguments are sent, and the child imports from them. _, reduced_args = _deep_reduce_pinned_memory_resource(pinned_ipc_resource) assert reduced_args[0] is pinned_ipc_resource.allocation_handle assert reduced_args[1] == pinned_ipc_resource.numa_id - run_child(child_import_reduced_args_without_location_query, reduced_args) - - @pytest.mark.agent_authored(model="claude-sonnet-5-5") - def test_pickle_omits_unknown_numa_id(self, pinned_ipc_resource): - run_child(child_reduce_imported_resource, pinned_ipc_resource.allocation_handle) + run_child(child_pickle_numa_id, reduced_args) @pytest.mark.agent_authored(model="claude-sonnet-5-5") def test_registered_import_rejects_conflicting_numa_id(self, pinned_ipc_resource): run_child(child_registered_import_rejects_conflicting_numa_id, pinned_ipc_resource.allocation_handle) @pytest.mark.agent_authored(model="claude-sonnet-5-5") - @pytest.mark.parametrize("numa_id", [-1, -5]) - def test_negative_numa_id_raises(self, numa_id): + def test_negative_numa_id_raises(self): # Rejected before the handle is used or CUDA is initialized. with pytest.raises(ValueError, match="numa_id"): - PinnedMemoryResource.from_allocation_handle(0, numa_id=numa_id) + PinnedMemoryResource.from_allocation_handle(0, numa_id=-1) From 308de2d7e09102aae9ab6393f3e307974c931186 Mon Sep 17 00:00:00 2001 From: Ralf Juengling Date: Wed, 25 Nov 2026 16:49:06 -0800 Subject: [PATCH 5/8] fix(cuda.core): apply numa_id to a registered pinned import with an unknown node A second import of a registered handle, given a numa_id, now sets the node of a resource whose first import had none, instead of leaving numa_id raising. --- .../core/_memory/_pinned_memory_resource.pyi | 8 +++--- .../core/_memory/_pinned_memory_resource.pyx | 25 +++++++++++++------ .../tests/memory_ipc/test_ipc_pool_kind.py | 15 +++++++---- 3 files changed, 32 insertions(+), 16 deletions(-) diff --git a/cuda_core/cuda/core/_memory/_pinned_memory_resource.pyi b/cuda_core/cuda/core/_memory/_pinned_memory_resource.pyi index 6ca2d3cc0066..0806592a7e4a 100644 --- a/cuda_core/cuda/core/_memory/_pinned_memory_resource.pyi +++ b/cuda_core/cuda/core/_memory/_pinned_memory_resource.pyi @@ -166,9 +166,11 @@ class PinnedMemoryResource(_MemPool): 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 node comes from neither the - driver nor this argument, the import succeeds but :attr:`numa_id` - raises ``RuntimeError``. Must be >= 0 if given. + 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 ------- diff --git a/cuda_core/cuda/core/_memory/_pinned_memory_resource.pyx b/cuda_core/cuda/core/_memory/_pinned_memory_resource.pyx index d478aba19355..f5a9006fe120 100644 --- a/cuda_core/cuda/core/_memory/_pinned_memory_resource.pyx +++ b/cuda_core/cuda/core/_memory/_pinned_memory_resource.pyx @@ -220,9 +220,11 @@ cdef class PinnedMemoryResource(_MemPool): 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 node comes from neither the - driver nor this argument, the import succeeds but :attr:`numa_id` - raises ``RuntimeError``. Must be >= 0 if given. + 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 ------- @@ -255,7 +257,7 @@ cdef class PinnedMemoryResource(_MemPool): _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_check_numa_id(mr, numa_id) + _PMR_apply_numa_id(mr, numa_id) return mr @property @@ -399,9 +401,16 @@ cdef inline int _PMR_grant_device_access( return 0 -cdef inline int _PMR_check_numa_id(PinnedMemoryResource self, object numa_id) except? -1: - # A node the caller passed must agree with a node that is known. - if numa_id is not None and self._numa_id_known and self._numa_id != numa_id: +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. + if numa_id is None: + return 0 + if not self._numa_id_known: + self._numa_id = numa_id + self._numa_id_known = True + elif self._numa_id != numa_id: raise ValueError( f"numa_id {numa_id} does not match the NUMA node of the memory pool, " f"which is {self._numa_id}") @@ -420,7 +429,7 @@ cdef int _PMR_init_imported(_MemPool mr, object numa_id) except? -1: 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_check_numa_id(self, numa_id) + _PMR_apply_numa_id(self, numa_id) elif numa_id is not None: self._numa_id = numa_id self._numa_id_known = True diff --git a/cuda_core/tests/memory_ipc/test_ipc_pool_kind.py b/cuda_core/tests/memory_ipc/test_ipc_pool_kind.py index b925bbfd8dea..0f30225f62e0 100644 --- a/cuda_core/tests/memory_ipc/test_ipc_pool_kind.py +++ b/cuda_core/tests/memory_ipc/test_ipc_pool_kind.py @@ -187,15 +187,20 @@ def child_pickle_numa_id(reduced_args): assert _deep_reduce_pinned_memory_resource(known)[1][1] == CLAIMED_NUMA_ID -def child_registered_import_rejects_conflicting_numa_id(alloc_handle): +def child_registered_import_applies_numa_id(alloc_handle): _without_location_query() device = Device() device.set_current() baseline = _live_owned_mempool_count() with contextlib.ExitStack() as stack: - mr = enter_imported_pool(stack, PinnedMemoryResource, device, alloc_handle, CLAIMED_NUMA_ID) - # The handle's UUID is now registered, so the resource is returned as is. + mr = enter_imported_pool(stack, PinnedMemoryResource, device, alloc_handle) + with pytest.raises(RuntimeError, match="NUMA node .* is not known"): + _ = mr.numa_id + # The handle's UUID is now registered, so the resource is returned, and + # it takes the node that its first import lacked. + assert PinnedMemoryResource.from_allocation_handle(alloc_handle, numa_id=CLAIMED_NUMA_ID) is mr + assert mr.numa_id == CLAIMED_NUMA_ID assert PinnedMemoryResource.from_allocation_handle(alloc_handle, numa_id=CLAIMED_NUMA_ID) is mr with pytest.raises(ValueError, match="numa_id"): PinnedMemoryResource.from_allocation_handle(alloc_handle, numa_id=CLAIMED_NUMA_ID + 1) @@ -380,8 +385,8 @@ def test_pickle_numa_id(self, pinned_ipc_resource): run_child(child_pickle_numa_id, reduced_args) @pytest.mark.agent_authored(model="claude-sonnet-5-5") - def test_registered_import_rejects_conflicting_numa_id(self, pinned_ipc_resource): - run_child(child_registered_import_rejects_conflicting_numa_id, pinned_ipc_resource.allocation_handle) + def test_registered_import_applies_numa_id(self, pinned_ipc_resource): + run_child(child_registered_import_applies_numa_id, pinned_ipc_resource.allocation_handle) @pytest.mark.agent_authored(model="claude-sonnet-5-5") def test_negative_numa_id_raises(self): From d516eed74a60fdc459152d331bd32b962802173c Mon Sep 17 00:00:00 2001 From: Ralf Juengling Date: Wed, 25 Nov 2026 17:33:56 -0800 Subject: [PATCH 6/8] fix(cuda.core): make the numa_id of a shared pinned import thread-safe Check and set the node of a registered import in one critical section, and read it under the same critical section in numa_id and the pickle reducer, so that concurrent imports naming different nodes cannot both succeed on a free-threaded build. The reducer no longer sends a negative node, which from_allocation_handle rejects. --- .../core/_memory/_pinned_memory_resource.pyx | 31 ++++++++++----- .../tests/memory_ipc/test_ipc_pool_kind.py | 38 +++++++++++++++++++ 2 files changed, 60 insertions(+), 9 deletions(-) diff --git a/cuda_core/cuda/core/_memory/_pinned_memory_resource.pyx b/cuda_core/cuda/core/_memory/_pinned_memory_resource.pyx index f5a9006fe120..882008e1e17f 100644 --- a/cuda_core/cuda/core/_memory/_pinned_memory_resource.pyx +++ b/cuda_core/cuda/core/_memory/_pinned_memory_resource.pyx @@ -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 ( @@ -278,6 +279,7 @@ 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. @@ -405,15 +407,21 @@ cdef inline int _PMR_apply_numa_id(PinnedMemoryResource self, object numa_id) ex # 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 - if not self._numa_id_known: - self._numa_id = numa_id - self._numa_id_known = True - elif self._numa_id != numa_id: - raise ValueError( - f"numa_id {numa_id} does not match the NUMA node of the memory pool, " - f"which is {self._numa_id}") + 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 @@ -442,8 +450,13 @@ def _deep_reduce_pinned_memory_resource(mr: object) -> tuple[object, ...]: 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. - return pmr.from_allocation_handle, (alloc_handle, pmr._numa_id if pmr._numa_id_known else None) + # 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) diff --git a/cuda_core/tests/memory_ipc/test_ipc_pool_kind.py b/cuda_core/tests/memory_ipc/test_ipc_pool_kind.py index 0f30225f62e0..46ae05903bcf 100644 --- a/cuda_core/tests/memory_ipc/test_ipc_pool_kind.py +++ b/cuda_core/tests/memory_ipc/test_ipc_pool_kind.py @@ -12,7 +12,9 @@ """ import contextlib +import functools import multiprocessing as mp +import threading import pytest from helpers.child_processes import run_child @@ -27,6 +29,7 @@ skip_if_host_numa_pinned_memory_unsupported, skip_if_pool_location_query_unsupported, ) +from helpers.misc import run_in_threads from cuda.bindings import driver from cuda.core import ( @@ -41,6 +44,7 @@ from cuda.core._memory._pinned_memory_resource import _deep_reduce_pinned_memory_resource NBYTES = 64 +THREADS = 4 # these tests spawn new processes and files which fails for very many threads; # child processes and IPC fixtures are shared across workers (#2784); cap at two threads @@ -209,6 +213,36 @@ def child_registered_import_applies_numa_id(alloc_handle): assert _live_owned_mempool_count() == baseline +def child_concurrent_numa_ids_agree(alloc_handle): + _without_location_query() + device = Device() + device.set_current() + baseline = _live_owned_mempool_count() + + with contextlib.ExitStack() as stack: + mr = enter_imported_pool(stack, PinnedMemoryResource, device, alloc_handle) + barrier = threading.Barrier(THREADS) + adopted = [] + + def importer(numa_id): + barrier.wait() + try: + PinnedMemoryResource.from_allocation_handle(alloc_handle, numa_id=numa_id) + except ValueError: + return + adopted.append(numa_id) + + # Each thread names a different node for a resource whose node is unknown. + run_in_threads( + [functools.partial(importer, CLAIMED_NUMA_ID + i) for i in range(THREADS)], + barrier=barrier, + timeout=60, + ) + # Exactly one node wins, and no import that named another node succeeds. + assert adopted == [mr.numa_id] + assert _live_owned_mempool_count() == baseline + + def child_numa_id_is_checked_against_driver(alloc_handle): device = Device() device.set_current() @@ -388,6 +422,10 @@ def test_pickle_numa_id(self, pinned_ipc_resource): def test_registered_import_applies_numa_id(self, pinned_ipc_resource): run_child(child_registered_import_applies_numa_id, pinned_ipc_resource.allocation_handle) + @pytest.mark.agent_authored(model="claude-opus-5-5") + def test_concurrent_imports_agree_on_numa_id(self, pinned_ipc_resource): + run_child(child_concurrent_numa_ids_agree, pinned_ipc_resource.allocation_handle) + @pytest.mark.agent_authored(model="claude-sonnet-5-5") def test_negative_numa_id_raises(self): # Rejected before the handle is used or CUDA is initialized. From 1f0258ca4f81aa8e546eae8a2c309a59722007e8 Mon Sep 17 00:00:00 2001 From: Ralf Juengling Date: Wed, 25 Nov 2026 17:35:01 -0800 Subject: [PATCH 7/8] docs(cuda.core): note that numa_id fills in an unknown node of a registered pinned import --- cuda_core/docs/source/release/1.4.0-notes.rst | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/cuda_core/docs/source/release/1.4.0-notes.rst b/cuda_core/docs/source/release/1.4.0-notes.rst index 543f057f63ba..22aabb1fee8a 100644 --- a/cuda_core/docs/source/release/1.4.0-notes.rst +++ b/cuda_core/docs/source/release/1.4.0-notes.rst @@ -65,9 +65,10 @@ Fixes and enhancements 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. ``from_allocation_handle`` - raises ``ValueError`` for a negative ``numa_id`` or one that differs from the - pool's known node. When the node can be neither queried nor taken from the + ``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 ``ValueError`` for a negative + ``numa_id`` 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 `__) From fde0453c42107fed420bdb055b8a9f6a61381c47 Mon Sep 17 00:00:00 2001 From: Ralf Juengling Date: Mon, 30 Nov 2026 13:59:12 -0800 Subject: [PATCH 8/8] fix(cuda.core): reject a non-integer numa_id and tighten the pinned numa_id tests from_allocation_handle normalizes numa_id with operator.index and bounds it by INT_MAX before importing the pool, so a float is no longer truncated. The pickle test now sends the resource through a multiprocessing Pipe, the rejected-import test closes the first import so that its cleanup is checked, the pinned IPC pool is a shared fixture, and the tests assert exception types instead of messages. --- .../core/_memory/_pinned_memory_resource.pyi | 7 +- .../core/_memory/_pinned_memory_resource.pyx | 17 ++- cuda_core/docs/source/release/1.4.0-notes.rst | 5 +- cuda_core/tests/conftest.py | 6 ++ .../tests/memory_ipc/test_ipc_pool_kind.py | 101 ++++++++---------- 5 files changed, 72 insertions(+), 64 deletions(-) diff --git a/cuda_core/cuda/core/_memory/_pinned_memory_resource.pyi b/cuda_core/cuda/core/_memory/_pinned_memory_resource.pyi index 0806592a7e4a..bc01164db503 100644 --- a/cuda_core/cuda/core/_memory/_pinned_memory_resource.pyi +++ b/cuda_core/cuda/core/_memory/_pinned_memory_resource.pyi @@ -184,10 +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 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 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: diff --git a/cuda_core/cuda/core/_memory/_pinned_memory_resource.pyx b/cuda_core/cuda/core/_memory/_pinned_memory_resource.pyx index 882008e1e17f..d2d7acfe566e 100644 --- a/cuda_core/cuda/core/_memory/_pinned_memory_resource.pyx +++ b/cuda_core/cuda/core/_memory/_pinned_memory_resource.pyx @@ -23,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 @@ -239,13 +241,18 @@ 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 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 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 and numa_id < 0: - raise ValueError(f"numa_id must be >= 0, got {numa_id}") + 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, diff --git a/cuda_core/docs/source/release/1.4.0-notes.rst b/cuda_core/docs/source/release/1.4.0-notes.rst index 22aabb1fee8a..f83634bd4326 100644 --- a/cuda_core/docs/source/release/1.4.0-notes.rst +++ b/cuda_core/docs/source/release/1.4.0-notes.rst @@ -67,8 +67,9 @@ Fixes and enhancements :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 ``ValueError`` for a negative - ``numa_id`` or one that differs from the pool's known node. When the node can be neither queried nor taken from the + 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 `__) diff --git a/cuda_core/tests/conftest.py b/cuda_core/tests/conftest.py index 0a8c9d44786c..f442bc325719 100644 --- a/cuda_core/tests/conftest.py +++ b/cuda_core/tests/conftest.py @@ -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.""" diff --git a/cuda_core/tests/memory_ipc/test_ipc_pool_kind.py b/cuda_core/tests/memory_ipc/test_ipc_pool_kind.py index b6cd29bf6bdc..49f2a575f0eb 100644 --- a/cuda_core/tests/memory_ipc/test_ipc_pool_kind.py +++ b/cuda_core/tests/memory_ipc/test_ipc_pool_kind.py @@ -129,10 +129,11 @@ def child_rejected_import_keeps_existing_import(mr_type, alloc_handle, descripto def child_imported_numa_id(alloc_handle, numa_id): - Device().set_current() - mr = PinnedMemoryResource.from_allocation_handle(alloc_handle) - assert mr.numa_id == numa_id - mr.close() + device = Device() + device.set_current() + with contextlib.ExitStack() as stack: + mr = enter_imported_pool(stack, PinnedMemoryResource, device, alloc_handle) + assert mr.numa_id == numa_id def child_unpickled_numa_id(mr, numa_id): @@ -163,26 +164,26 @@ def child_import_with_numa_id_without_location_query(alloc_handle): # A raw file descriptor carries no UUID, so each import is a separate resource. with contextlib.ExitStack() as stack: omitted = enter_imported_pool(stack, PinnedMemoryResource, device, int(alloc_handle)) - with pytest.raises(RuntimeError, match="NUMA node .* is not known"): + with pytest.raises(RuntimeError): _ = omitted.numa_id given = enter_imported_pool(stack, PinnedMemoryResource, device, int(alloc_handle), CLAIMED_NUMA_ID) assert given.numa_id == CLAIMED_NUMA_ID -def child_pickle_numa_id(reduced_args): +def child_pickle_numa_id(conn, alloc_handle, numa_id): _without_location_query() device = Device() device.set_current() - alloc_handle, numa_id = reduced_args with contextlib.ExitStack() as stack: - # Importing from the exporter's reducer output yields the exporter's node. - mr = enter_imported_pool(stack, PinnedMemoryResource, device, alloc_handle, numa_id) + # Receiving the resource unpickles it, which imports the pool without a + # location query. The patch above has to come first, so the resource + # cannot be an argument of run_child, which unpickles before this runs. + mr = stack.enter_context(contextlib.closing(conn.recv())) assert mr.numa_id == numa_id - # A third process would have to patch driver_version before unpickling, as - # this test does, so the reducer's output is checked here. - # The node of this import is unknown, so a third process must not be told a node. + # An imported resource sends on only a node it knows. The reducer is + # called directly because a third process would need the same patch. unknown = enter_imported_pool(stack, PinnedMemoryResource, device, int(alloc_handle)) assert _deep_reduce_pinned_memory_resource(unknown)[1][1] is None @@ -198,14 +199,14 @@ def child_registered_import_applies_numa_id(alloc_handle): with contextlib.ExitStack() as stack: mr = enter_imported_pool(stack, PinnedMemoryResource, device, alloc_handle) - with pytest.raises(RuntimeError, match="NUMA node .* is not known"): + with pytest.raises(RuntimeError): _ = mr.numa_id # The handle's UUID is now registered, so the resource is returned, and # it takes the node that its first import lacked. assert PinnedMemoryResource.from_allocation_handle(alloc_handle, numa_id=CLAIMED_NUMA_ID) is mr assert mr.numa_id == CLAIMED_NUMA_ID assert PinnedMemoryResource.from_allocation_handle(alloc_handle, numa_id=CLAIMED_NUMA_ID) is mr - with pytest.raises(ValueError, match="numa_id"): + with pytest.raises(ValueError): PinnedMemoryResource.from_allocation_handle(alloc_handle, numa_id=CLAIMED_NUMA_ID + 1) assert PinnedMemoryResource.from_allocation_handle(alloc_handle) is mr assert mr.numa_id == CLAIMED_NUMA_ID @@ -247,14 +248,18 @@ def child_numa_id_is_checked_against_driver(alloc_handle): device.set_current() baseline = _live_owned_mempool_count() - with contextlib.ExitStack() as stack: - mr = enter_imported_pool(stack, PinnedMemoryResource, device, int(alloc_handle)) - node = mr.numa_id - # Releasing the rejected import cannot raise; a failed cuMemPoolDestroy - # surfaces only as a CUDAWarning. - with assert_no_cuda_warning(), pytest.raises(ValueError, match="numa_id"): - PinnedMemoryResource.from_allocation_handle(int(alloc_handle), numa_id=node + 1) + first = import_pool_resource(PinnedMemoryResource, device, int(alloc_handle)) + node = first.numa_id + # Imports of one pool share a native owner that releases the driver's + # references only when the last import closes. Close the first so that the + # rejected import below is the last one and its release happens in the capture. + first.close() + # Releasing the rejected import cannot raise; a failed cuMemPoolDestroy + # surfaces only as a CUDAWarning. + with assert_no_cuda_warning(), pytest.raises(ValueError): + PinnedMemoryResource.from_allocation_handle(int(alloc_handle), numa_id=node + 1) + with contextlib.ExitStack() as stack: matching = enter_imported_pool(stack, PinnedMemoryResource, device, int(alloc_handle), node) assert matching.numa_id == node assert _live_owned_mempool_count() == baseline @@ -302,15 +307,6 @@ def _set_start_method(self): with contextlib.suppress(RuntimeError): mp.set_start_method("spawn", force=True) - @pytest.fixture - def pinned_ipc_resource(self, ipc_device): - skip_if_host_numa_pinned_memory_unsupported(ipc_device) - ipc_device.set_current() - mr = PinnedMemoryResource(PinnedMemoryResourceOptions(max_size=POOL_SIZE, ipc_enabled=True)) - yield mr - mr.close() - ipc_device.sync() - @pytest.fixture def exported_buffer(self, ipc_device, ipc_pool_memory_resource): ipc_device.set_current() @@ -381,46 +377,43 @@ def test_imported_pinned_resource_reports_numa_id(self, ipc_device): pytest.skip("needs a host NUMA node other than 0 with memory") ipc_device.set_current() mr = PinnedMemoryResource(PinnedMemoryResourceOptions(max_size=POOL_SIZE, ipc_enabled=True, numa_id=numa_id)) - try: + with contextlib.closing(mr): assert mr.numa_id == numa_id run_child(child_imported_numa_id, mr.allocation_handle, numa_id) # Unpickling the resource is the other import path. run_child(child_unpickled_numa_id, mr, numa_id) - finally: - mr.close() @pytest.mark.agent_authored(model="claude-sonnet-5-5") - def test_numa_id_is_checked_against_driver(self, pinned_ipc_resource): - run_child(child_numa_id_is_checked_against_driver, pinned_ipc_resource.allocation_handle) + def test_numa_id_is_checked_against_driver(self, ipc_pinned_memory_resource): + run_child(child_numa_id_is_checked_against_driver, ipc_pinned_memory_resource.allocation_handle) class TestPinnedImportNumaId(_IpcPoolFixtures): """Without a location query, an imported pinned pool's node comes from the caller or the pickle (#3508).""" @pytest.mark.agent_authored(model="claude-sonnet-5-5") - def test_import_uses_given_numa_id(self, pinned_ipc_resource): - run_child(child_import_with_numa_id_without_location_query, pinned_ipc_resource.allocation_handle) + def test_import_uses_given_numa_id(self, ipc_pinned_memory_resource): + run_child(child_import_with_numa_id_without_location_query, ipc_pinned_memory_resource.allocation_handle) - @pytest.mark.agent_authored(model="claude-sonnet-5-5") - def test_pickle_numa_id(self, pinned_ipc_resource): - # The child must patch driver_version before it imports the pool, but - # run_child unpickles a resource argument before the child runs. So the - # reducer's arguments are sent, and the child imports from them. - _, reduced_args = _deep_reduce_pinned_memory_resource(pinned_ipc_resource) - assert reduced_args[0] is pinned_ipc_resource.allocation_handle - assert reduced_args[1] == pinned_ipc_resource.numa_id - run_child(child_pickle_numa_id, reduced_args) + @pytest.mark.agent_authored(model="claude-opus-5-5") + def test_pickle_numa_id(self, ipc_pinned_memory_resource): + mr = ipc_pinned_memory_resource + parent_conn, child_conn = mp.Pipe() + with parent_conn, child_conn: + parent_conn.send(mr) + run_child(child_pickle_numa_id, child_conn, mr.allocation_handle, mr.numa_id) @pytest.mark.agent_authored(model="claude-sonnet-5-5") - def test_registered_import_applies_numa_id(self, pinned_ipc_resource): - run_child(child_registered_import_applies_numa_id, pinned_ipc_resource.allocation_handle) + def test_registered_import_applies_numa_id(self, ipc_pinned_memory_resource): + run_child(child_registered_import_applies_numa_id, ipc_pinned_memory_resource.allocation_handle) @pytest.mark.agent_authored(model="claude-opus-5-5") - def test_concurrent_imports_agree_on_numa_id(self, pinned_ipc_resource): - run_child(child_concurrent_numa_ids_agree, pinned_ipc_resource.allocation_handle) + def test_concurrent_imports_agree_on_numa_id(self, ipc_pinned_memory_resource): + run_child(child_concurrent_numa_ids_agree, ipc_pinned_memory_resource.allocation_handle) - @pytest.mark.agent_authored(model="claude-sonnet-5-5") - def test_negative_numa_id_raises(self): + @pytest.mark.agent_authored(model="claude-opus-5-5") + @pytest.mark.parametrize(("numa_id", "error"), [(-1, ValueError), (2**40, ValueError), (1.75, TypeError)]) + def test_invalid_numa_id_raises(self, numa_id, error): # Rejected before the handle is used or CUDA is initialized. - with pytest.raises(ValueError, match="numa_id"): - PinnedMemoryResource.from_allocation_handle(0, numa_id=-1) + with pytest.raises(error): + PinnedMemoryResource.from_allocation_handle(0, numa_id=numa_id)