Repository navigation
fix(cuda.core): pickle memory-resource devices by UUID for IPC #3126
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Andy-Jost
wants to merge
3
commits into
NVIDIA:main
Choose a base branch
from
Andy-Jost:ajost/ipc-pickle-device-uuid
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+289
−13
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,195 @@ | ||
| # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
| # SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| """Resources sent to another process keep their devices when the ordinals differ (issue #3097). | ||
|
|
||
| The child process sees the parent's two devices in reversed order, so each | ||
| ordinal names the other device there. The child must still rebuild the | ||
| resource for the device that owns the memory, and the peers of a | ||
| ``VirtualMemoryResource`` must name the same devices as in the parent. | ||
| """ | ||
|
|
||
| import contextlib | ||
| import ctypes | ||
| import multiprocessing as mp | ||
| import os | ||
|
|
||
| import pytest | ||
| from helpers.child_processes import child_timeout_sec, kill_subprocesses | ||
| from helpers.constants import POOL_SIZE | ||
|
|
||
| from cuda.bindings import driver | ||
| from cuda.core import ( | ||
| Buffer, | ||
| Device, | ||
| DeviceMemoryResource, | ||
| DeviceMemoryResourceOptions, | ||
| VirtualMemoryResource, | ||
| VirtualMemoryResourceOptions, | ||
| ) | ||
| from cuda.core._utils.cuda_utils import handle_return | ||
|
|
||
| CHILD_TIMEOUT_SEC = child_timeout_sec() | ||
| NBYTES = 64 | ||
| PATTERN = 0x5A | ||
|
|
||
|
|
||
| @contextlib.contextmanager | ||
| def _visible_devices(*devices): | ||
| """Make only ``devices``, in this order, visible to processes started in the block. | ||
|
|
||
| The spawn start method copies ``os.environ`` when ``Process.start()`` runs. | ||
| The devices are named by UUID, so the order does not depend on how this | ||
| process numbers them. | ||
| """ | ||
| saved = os.environ.get("CUDA_VISIBLE_DEVICES") | ||
| os.environ["CUDA_VISIBLE_DEVICES"] = ",".join(f"GPU-{device.uuid}" for device in devices) | ||
| try: | ||
| yield | ||
| finally: | ||
| if saved is None: | ||
| del os.environ["CUDA_VISIBLE_DEVICES"] | ||
| else: | ||
| os.environ["CUDA_VISIBLE_DEVICES"] = saved | ||
|
|
||
|
|
||
| def _send_to_child(obj, visible): | ||
| """Send ``obj`` to a child that sees only ``visible``, and return the child's report.""" | ||
| inbox, outbox = mp.Queue(), mp.Queue() | ||
| process = mp.Process(target=_child_main, args=(inbox, outbox)) | ||
| with _visible_devices(*visible): | ||
| process.start() | ||
| inbox.put(obj) | ||
| try: | ||
| return outbox.get(timeout=CHILD_TIMEOUT_SEC) | ||
| finally: | ||
| process.join(timeout=CHILD_TIMEOUT_SEC) | ||
| survivors = kill_subprocesses(process) | ||
| assert not survivors, "child did not exit within timeout" | ||
| assert process.exitcode == 0, f"child exited with {process.exitcode}" | ||
|
|
||
|
|
||
| def _child_main(inbox, outbox): | ||
| try: | ||
| report = _receive(inbox.get(timeout=CHILD_TIMEOUT_SEC)) | ||
| except Exception as exc: # report every failure to the parent, which asserts on it | ||
| report = {"error": type(exc).__name__, "message": str(exc)} | ||
| outbox.put(report) | ||
|
|
||
|
|
||
| def _receive(obj): | ||
| """Describe the received buffer in terms of device UUIDs, which do not depend on the ordinals.""" | ||
| if not isinstance(obj, Buffer): | ||
| return {"received": type(obj).__name__} | ||
| mr = obj.memory_resource | ||
| report = {"device_id": obj.device_id, "device_uuid": Device(obj.device_id).uuid} | ||
| host = (ctypes.c_ubyte * NBYTES)() | ||
| handle_return(driver.cuMemcpyDtoH(ctypes.addressof(host), int(obj.handle), NBYTES)) | ||
| report["data"] = bytes(host) | ||
| if isinstance(mr, VirtualMemoryResource): | ||
| report["peer_uuids"] = [Device(peer).uuid for peer in mr.config.peers] | ||
| report["peer_access"] = [_access_flags(obj, peer) for peer in mr.config.peers] | ||
| obj.close() | ||
| return report | ||
|
|
||
|
|
||
| def _access_flags(buf, device_id): | ||
| """The access a device has to ``buf``: 0 for none, 3 for read-write.""" | ||
| location = driver.CUmemLocation() | ||
| location.type = driver.CUmemLocationType.CU_MEM_LOCATION_TYPE_DEVICE | ||
| location.id = device_id | ||
| return int(handle_return(driver.cuMemGetAccess(location, int(buf.handle)))) | ||
|
|
||
|
|
||
| def _fill(device, buf): | ||
| device.set_current() | ||
| handle_return(driver.cuMemsetD8(int(buf.handle), PATTERN, NBYTES)) | ||
| device.sync() | ||
|
|
||
|
|
||
| def _vmm_resource(device, peers=()): | ||
| return VirtualMemoryResource(device, config=VirtualMemoryResourceOptions(handle_type="posix_fd", peers=peers)) | ||
|
|
||
|
|
||
| def _check_report(report, owner): | ||
| assert "error" not in report, f"the child could not receive the buffer: {report}" | ||
| # The child numbers the devices the other way round; otherwise this test proves nothing. | ||
| assert report["device_id"] != owner.device_id, "CUDA_VISIBLE_DEVICES did not reorder the devices in the child" | ||
| assert report["device_uuid"] == owner.uuid | ||
| assert report["data"] == bytes([PATTERN]) * NBYTES | ||
|
|
||
|
|
||
| @pytest.mark.agent_authored(model="claude-opus-5-5") | ||
| @pytest.mark.thread_unsafe(reason="sets CUDA_VISIBLE_DEVICES, which is process-global") | ||
| def test_device_memory_resource_buffer(ipc_mempool_device_x2): | ||
| """A pool-backed buffer comes back on the device that owns it, not on the device with the same ordinal.""" | ||
| dev0, dev1 = ipc_mempool_device_x2 | ||
| mr = DeviceMemoryResource(dev0, options=DeviceMemoryResourceOptions(max_size=POOL_SIZE, ipc_enabled=True)) | ||
| buf = mr.allocate(NBYTES, stream=dev0.default_stream) | ||
| _fill(dev0, buf) | ||
|
|
||
| report = _send_to_child(buf, visible=(dev1, dev0)) | ||
| _check_report(report, dev0) | ||
|
|
||
| buf.close() | ||
| dev0.sync() | ||
| mr.close() | ||
|
|
||
|
|
||
| @pytest.mark.agent_authored(model="claude-opus-5-5") | ||
| @pytest.mark.thread_unsafe(reason="sets CUDA_VISIBLE_DEVICES, which is process-global") | ||
| def test_virtual_memory_resource_buffer(vmm_ipc_device_x2): | ||
| """A VirtualMemoryResource buffer comes back on the device that owns it.""" | ||
| dev0, dev1 = vmm_ipc_device_x2 | ||
| mr = _vmm_resource(dev0) | ||
| buf = mr.allocate(NBYTES) | ||
| _fill(dev0, buf) | ||
|
|
||
| report = _send_to_child(buf, visible=(dev1, dev0)) | ||
| _check_report(report, dev0) | ||
| assert report["peer_uuids"] == [] | ||
|
|
||
| buf.close() | ||
| dev0.sync() | ||
|
|
||
|
|
||
| @pytest.mark.agent_authored(model="claude-opus-5-5") | ||
| @pytest.mark.thread_unsafe(reason="sets CUDA_VISIBLE_DEVICES, which is process-global") | ||
| def test_virtual_memory_resource_peers(vmm_ipc_device_x2): | ||
| """The peers of a VirtualMemoryResource name the same devices in the child, and those devices get access.""" | ||
| dev0, dev1 = vmm_ipc_device_x2 | ||
| if not dev1.can_access_peer(dev0): | ||
| pytest.skip("Test requires peer access from the second device to the first") | ||
| mr = _vmm_resource(dev0, peers=(dev1.device_id,)) | ||
| buf = mr.allocate(NBYTES) | ||
| _fill(dev0, buf) | ||
|
|
||
| report = _send_to_child(buf, visible=(dev1, dev0)) | ||
| _check_report(report, dev0) | ||
| assert report["peer_uuids"] == [dev1.uuid] | ||
| assert report["peer_access"] == [3] | ||
|
|
||
| buf.close() | ||
| dev0.sync() | ||
|
|
||
|
|
||
| @pytest.mark.agent_authored(model="claude-opus-5-5") | ||
| @pytest.mark.thread_unsafe(reason="sets CUDA_VISIBLE_DEVICES, which is process-global") | ||
| @pytest.mark.parametrize("kind", ["device", "vmm"]) | ||
| def test_owning_device_not_visible(request, kind): | ||
| """A child that cannot see the owning device refuses the resource and names the missing UUID.""" | ||
| if kind == "device": | ||
| dev0, dev1 = request.getfixturevalue("ipc_mempool_device_x2") | ||
| mr = DeviceMemoryResource(dev0, options=DeviceMemoryResourceOptions(max_size=POOL_SIZE, ipc_enabled=True)) | ||
| else: | ||
| dev0, dev1 = request.getfixturevalue("vmm_ipc_device_x2") | ||
| mr = _vmm_resource(dev0) | ||
|
|
||
| # The child receives the resource itself: it fails before it needs any buffer's handles. | ||
| report = _send_to_child(mr, visible=(dev1,)) | ||
| assert report["error"] == "RuntimeError", report | ||
| assert f"no CUDA device visible to this process has UUID {dev0.uuid}" in report["message"] | ||
| assert dev1.uuid in report["message"] | ||
|
|
||
| if kind == "device": | ||
| mr.close() |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win
important: Preserve peers from one-shot iterables.
If
VirtualMemoryResourceOptions.peersis a generator, allocation consumes it in_fill_access. A later buffer pickle serializes no peer UUIDs. The receiving resource then omits access for a peer that could access the exported buffer. Storepeersas a reusable tuple when the resource accepts its configuration, and test a buffer transfer with generator-supplied peers.