Source code for gs_nyx.nyx_external_memory

"""Import the GPU buffers Nyx exports into the compute API behind torch, CUDA or HIP.

Nyx exports a buffer as an OS handle (``EExternalMemoryHandleType``) with its allocation size and the identity of its
GPU (``DeviceIdentity``). :class:`NyxExternalMemoryImporter` pairs the compute device with that GPU, imports the handle
through the vendor driver already loaded by torch (``ctypes``, no package dependency) and wraps the mapped
pointer as a torch tensor through the CUDA array interface, zero copy.

Synchronization is on the CPU: call :meth:`NyxExternalMemoryImporter.synchronize` after writing and before Nyx
reads; Nyx waits for its own GPU work before returning. Release every imported buffer before Nyx destroys it.
"""

# External imports
import ctypes
import os
import sys

import torch

__all__ = ["NyxExternalMemoryError", "NyxExternalMemoryImporter", "NyxImportedBuffer"]


[docs] class NyxExternalMemoryError(RuntimeError): """A compute API call of the import failed."""
# Nyx's EExternalMemoryHandleType values (gs_nyx.nyx_py_sdk.EExternalMemoryHandleType), by integer value. _NYX_OPAQUE_FD = 0 _NYX_OPAQUE_WIN32 = 1 _NYX_D3D12_HEAP = 2 # Nyx's EDeviceIdentityType values (gs_nyx.nyx_py_sdk.EDeviceIdentityType), by integer value. _NYX_IDENTITY_LUID = 0 _NYX_IDENTITY_PCI_BUS = 1 # CUDA and HIP agree on the external memory handle type codes and on the dedicated flag. _HANDLE_TYPE_CODES = { _NYX_OPAQUE_FD: 1, # CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD / hipExternalMemoryHandleTypeOpaqueFd _NYX_OPAQUE_WIN32: 2, # CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32 / hipExternalMemoryHandleTypeOpaqueWin32 _NYX_D3D12_HEAP: 4, # CU_EXTERNAL_MEMORY_HANDLE_TYPE_D3D12_HEAP / hipExternalMemoryHandleTypeD3D12Heap } _EXTERNAL_MEMORY_DEDICATED = 0x1 # numpy-style type strings of the CUDA array interface, per torch dtype _TYPESTR = { torch.float32: "<f4", torch.float16: "<f2", torch.float64: "<f8", torch.int32: "<i4", torch.int64: "<i8", torch.uint8: "|u1", torch.int8: "|i1", } class _Win32Handle(ctypes.Structure): _fields_ = [("handle", ctypes.c_void_p), ("name", ctypes.c_void_p)] class _HandleDescUnion(ctypes.Union): _fields_ = [ ("fd", ctypes.c_int), ("win32", _Win32Handle), ("nvSciBufObject", ctypes.c_void_p), ] # CUDA_EXTERNAL_MEMORY_HANDLE_DESC and hipExternalMemoryHandleDesc share this layout class _ExternalMemoryHandleDesc(ctypes.Structure): _fields_ = [ ("type", ctypes.c_uint), ("handle", _HandleDescUnion), ("size", ctypes.c_ulonglong), ("flags", ctypes.c_uint), ("reserved", ctypes.c_uint * 16), ] # CUDA_EXTERNAL_MEMORY_BUFFER_DESC and hipExternalMemoryBufferDesc share this layout class _ExternalMemoryBufferDesc(ctypes.Structure): _fields_ = [ ("offset", ctypes.c_ulonglong), ("size", ctypes.c_ulonglong), ("flags", ctypes.c_uint), ("reserved", ctypes.c_uint * 16), ] def _parse_pci_bus_id(bus_id: str) -> tuple[int, int, int, int]: """Split a ``domain:bus:device.function`` string, as the compute APIs print it, into its four numbers.""" domain, bus, device_function = bus_id.split(":") device, function = device_function.split(".") return int(domain, 16), int(bus, 16), int(device, 16), int(function, 16) def _close_os_handle(handle: int, handle_type: int, imported: bool) -> None: """Release the exported handle, whether the import succeeded or not.""" if handle_type == _NYX_OPAQUE_FD: # A successful import consumes the fd if not imported: os.close(handle) return if sys.platform == "win32": ctypes.windll.kernel32.CloseHandle(ctypes.c_void_p(handle)) class _CudaDriver: """The handful of CUDA driver API entry points the import needs.""" name = "CUDA" def __init__(self): lib_name = "nvcuda.dll" if sys.platform == "win32" else "libcuda.so.1" try: self._lib = ( ctypes.WinDLL(lib_name) if sys.platform == "win32" else ctypes.CDLL(lib_name) ) except OSError as e: raise NyxExternalMemoryError( f"CUDA driver library '{lib_name}' not found: {e}" ) from e lib = self._lib lib.cuInit.argtypes = [ctypes.c_uint] lib.cuGetErrorString.argtypes = [ctypes.c_int, ctypes.POINTER(ctypes.c_char_p)] lib.cuDeviceGetCount.argtypes = [ctypes.POINTER(ctypes.c_int)] lib.cuDeviceGet.argtypes = [ctypes.POINTER(ctypes.c_int), ctypes.c_int] lib.cuDeviceGetLuid.argtypes = [ ctypes.c_char_p, ctypes.POINTER(ctypes.c_uint), ctypes.c_int, ] lib.cuDeviceGetPCIBusId.argtypes = [ctypes.c_char_p, ctypes.c_int, ctypes.c_int] lib.cuDevicePrimaryCtxRetain.argtypes = [ ctypes.POINTER(ctypes.c_void_p), ctypes.c_int, ] lib.cuDevicePrimaryCtxRelease_v2.argtypes = [ctypes.c_int] lib.cuCtxPushCurrent_v2.argtypes = [ctypes.c_void_p] lib.cuCtxPopCurrent_v2.argtypes = [ctypes.POINTER(ctypes.c_void_p)] lib.cuImportExternalMemory.argtypes = [ ctypes.POINTER(ctypes.c_void_p), ctypes.POINTER(_ExternalMemoryHandleDesc), ] lib.cuExternalMemoryGetMappedBuffer.argtypes = [ ctypes.POINTER(ctypes.c_ulonglong), ctypes.c_void_p, ctypes.POINTER(_ExternalMemoryBufferDesc), ] lib.cuDestroyExternalMemory.argtypes = [ctypes.c_void_p] lib.cuMemFree_v2.argtypes = [ctypes.c_ulonglong] self._check(lib.cuInit(0), "cuInit") def _check(self, status: int, call: str) -> None: if status != 0: msg = ctypes.c_char_p() self._lib.cuGetErrorString(status, ctypes.byref(msg)) text = msg.value.decode() if msg.value else "unknown" raise NyxExternalMemoryError(f"{call} failed: {text} ({status})") def device_count(self) -> int: count = ctypes.c_int(0) self._check(self._lib.cuDeviceGetCount(ctypes.byref(count)), "cuDeviceGetCount") return count.value def device_luid(self, index: int) -> tuple[bytes, int] | None: """The LUID and node mask of the device, or None where the platform has no LUID.""" if sys.platform != "win32": return None device = ctypes.c_int(0) self._check(self._lib.cuDeviceGet(ctypes.byref(device), index), "cuDeviceGet") luid = ctypes.create_string_buffer(8) node_mask = ctypes.c_uint(0) self._check( self._lib.cuDeviceGetLuid(luid, ctypes.byref(node_mask), device), "cuDeviceGetLuid", ) return luid.raw, node_mask.value def device_pci_bus(self, index: int) -> tuple[int, int, int, int] | None: device = ctypes.c_int(0) self._check(self._lib.cuDeviceGet(ctypes.byref(device), index), "cuDeviceGet") bus_id = ctypes.create_string_buffer(32) self._check( self._lib.cuDeviceGetPCIBusId(bus_id, len(bus_id), device), "cuDeviceGetPCIBusId", ) return _parse_pci_bus_id(bus_id.value.decode()) def retain_context(self, index: int) -> int: """Retain the device's primary context, the one torch runs on.""" device = ctypes.c_int(0) self._check(self._lib.cuDeviceGet(ctypes.byref(device), index), "cuDeviceGet") context = ctypes.c_void_p() self._check( self._lib.cuDevicePrimaryCtxRetain(ctypes.byref(context), device), "cuDevicePrimaryCtxRetain", ) return context.value def release_context(self, index: int) -> None: device = ctypes.c_int(0) self._check(self._lib.cuDeviceGet(ctypes.byref(device), index), "cuDeviceGet") self._lib.cuDevicePrimaryCtxRelease_v2(device) def push_context(self, context: int) -> None: self._check( self._lib.cuCtxPushCurrent_v2(ctypes.c_void_p(context)), "cuCtxPushCurrent" ) def pop_context(self) -> None: popped = ctypes.c_void_p() self._lib.cuCtxPopCurrent_v2(ctypes.byref(popped)) def import_memory(self, desc: _ExternalMemoryHandleDesc) -> int: memory = ctypes.c_void_p() self._check( self._lib.cuImportExternalMemory(ctypes.byref(memory), ctypes.byref(desc)), "cuImportExternalMemory", ) return memory.value def map_buffer(self, memory: int, desc: _ExternalMemoryBufferDesc) -> int: ptr = ctypes.c_ulonglong(0) self._check( self._lib.cuExternalMemoryGetMappedBuffer( ctypes.byref(ptr), ctypes.c_void_p(memory), ctypes.byref(desc) ), "cuExternalMemoryGetMappedBuffer", ) return ptr.value def unmap_buffer(self, ptr: int) -> None: self._lib.cuMemFree_v2(ctypes.c_ulonglong(ptr)) def destroy_memory(self, memory: int) -> None: self._lib.cuDestroyExternalMemory(ctypes.c_void_p(memory)) class _HipRuntime: """The handful of HIP runtime entry points the import needs.""" name = "HIP" def __init__(self): self._lib = self._load() self._previous_devices: list[int] = [] lib = self._lib lib.hipGetErrorString.restype = ctypes.c_char_p lib.hipGetErrorString.argtypes = [ctypes.c_int] lib.hipGetDeviceCount.argtypes = [ctypes.POINTER(ctypes.c_int)] lib.hipGetDevice.argtypes = [ctypes.POINTER(ctypes.c_int)] lib.hipSetDevice.argtypes = [ctypes.c_int] lib.hipImportExternalMemory.argtypes = [ ctypes.POINTER(ctypes.c_void_p), ctypes.POINTER(_ExternalMemoryHandleDesc), ] lib.hipExternalMemoryGetMappedBuffer.argtypes = [ ctypes.POINTER(ctypes.c_void_p), ctypes.c_void_p, ctypes.POINTER(_ExternalMemoryBufferDesc), ] lib.hipDestroyExternalMemory.argtypes = [ctypes.c_void_p] lib.hipFree.argtypes = [ctypes.c_void_p] lib.hipDeviceGetPCIBusId.argtypes = [ ctypes.c_char_p, ctypes.c_int, ctypes.c_int, ] # The properties entry point is versioned by the struct layout it fills; R0600 is the layout with # the luid fields right after the name and uuid, which is the one read below. self._get_properties = ( getattr(lib, "hipGetDevicePropertiesR0600", None) or lib.hipGetDeviceProperties ) self._get_properties.argtypes = [ctypes.c_void_p, ctypes.c_int] @staticmethod def _load(): """Return the HIP runtime torch already holds, a second runtime instance cannot use its mappings.""" torch.cuda.init() if sys.platform == "win32": kernel32 = ctypes.windll.kernel32 kernel32.GetModuleHandleW.restype = ctypes.c_void_p kernel32.GetModuleHandleW.argtypes = [ctypes.c_wchar_p] for name in ("amdhip64_7.dll", "amdhip64_6.dll", "amdhip64.dll"): handle = kernel32.GetModuleHandleW(name) if handle: return ctypes.WinDLL(name, handle=handle) raise NyxExternalMemoryError( "No HIP runtime is loaded in the process; is this torch a ROCm build?" ) for name in ("libamdhip64.so.7", "libamdhip64.so.6", "libamdhip64.so"): try: return ctypes.CDLL(name, mode=os.RTLD_NOLOAD | os.RTLD_GLOBAL) except OSError: continue raise NyxExternalMemoryError( "No HIP runtime is loaded in the process; is this torch a ROCm build?" ) def _check(self, status: int, call: str) -> None: if status != 0: text = self._lib.hipGetErrorString(status) text = text.decode() if text else "unknown" raise NyxExternalMemoryError(f"{call} failed: {text} ({status})") def device_count(self) -> int: count = ctypes.c_int(0) self._check( self._lib.hipGetDeviceCount(ctypes.byref(count)), "hipGetDeviceCount" ) return count.value def _properties(self, index: int) -> bytes: # hipDeviceProp_t is a few kilobytes; an oversized buffer absorbs any growth of the struct props = ctypes.create_string_buffer(8192) self._check(self._get_properties(props, index), "hipGetDeviceProperties") return props.raw def device_luid(self, index: int) -> tuple[bytes, int] | None: """The LUID and node mask of the device, or None where the platform has no LUID.""" if sys.platform != "win32": return None # hipDeviceProp_t: char name[256]; hipUUID uuid (16 bytes); char luid[8]; unsigned int luidDeviceNodeMask; ... props = self._properties(index) return props[272:280], int.from_bytes(props[280:284], "little") def device_pci_bus(self, index: int) -> tuple[int, int, int, int] | None: bus_id = ctypes.create_string_buffer(32) self._check( self._lib.hipDeviceGetPCIBusId(bus_id, len(bus_id), index), "hipDeviceGetPCIBusId", ) return _parse_pci_bus_id(bus_id.value.decode()) def retain_context(self, index: int) -> int: # HIP has no context object; the device is selected per call return index def release_context(self, index: int) -> None: pass def push_context(self, context: int) -> None: # The current device is thread state torch relies on, pop_context restores it previous = ctypes.c_int(0) self._check(self._lib.hipGetDevice(ctypes.byref(previous)), "hipGetDevice") self._check(self._lib.hipSetDevice(context), "hipSetDevice") self._previous_devices.append(previous.value) def pop_context(self) -> None: self._lib.hipSetDevice(self._previous_devices.pop()) def import_memory(self, desc: _ExternalMemoryHandleDesc) -> int: memory = ctypes.c_void_p() self._check( self._lib.hipImportExternalMemory(ctypes.byref(memory), ctypes.byref(desc)), "hipImportExternalMemory", ) return memory.value def map_buffer(self, memory: int, desc: _ExternalMemoryBufferDesc) -> int: ptr = ctypes.c_void_p() self._check( self._lib.hipExternalMemoryGetMappedBuffer( ctypes.byref(ptr), ctypes.c_void_p(memory), ctypes.byref(desc) ), "hipExternalMemoryGetMappedBuffer", ) return ptr.value def unmap_buffer(self, ptr: int) -> None: self._lib.hipFree(ctypes.c_void_p(ptr)) def destroy_memory(self, memory: int) -> None: self._lib.hipDestroyExternalMemory(ctypes.c_void_p(memory)) class _DevicePointerArray: """Exposes a device pointer through the CUDA array interface so torch can wrap it.""" def __init__(self, ptr: int, shape, typestr: str): self.__cuda_array_interface__ = { "shape": tuple(shape), "typestr": typestr, "data": (ptr, False), "version": 3, "strides": None, }
[docs] class NyxImportedBuffer: """A Nyx buffer mapped into the compute API. Create it through :meth:`NyxExternalMemoryImporter.import_buffer`."""
[docs] def __init__( self, importer: "NyxExternalMemoryImporter", memory: int, device_ptr: int, size: int, ): self._importer = importer self._memory = memory self.device_ptr = device_ptr self.size = size self._tensors: list[torch.Tensor] = []
@property def torch_device(self) -> torch.device: return self._importer.torch_device
[docs] def tensor(self, shape, dtype=torch.float32) -> torch.Tensor: """Return a torch tensor of the given shape and dtype aliasing the start of the buffer, zero copy.""" numel = 1 for dim in shape: numel *= int(dim) element_size = torch.empty((), dtype=dtype).element_size() if numel * element_size > self.size: raise ValueError( f"NyxImportedBuffer: a {tuple(shape)} {dtype} tensor needs {numel * element_size} bytes, the buffer holds {self.size}." ) array = _DevicePointerArray(self.device_ptr, shape, _TYPESTR[dtype]) tensor = torch.as_tensor(array, device=self.torch_device) self._tensors.append(tensor) return tensor
[docs] def release(self) -> None: """Unmap the buffer and drop the import. Every tensor returned by :meth:`tensor` is dangling afterwards.""" if self._memory is None: return self._tensors = [] api = self._importer._api self._importer._push() try: api.unmap_buffer(self.device_ptr) api.destroy_memory(self._memory) finally: self._importer._pop() self._memory = None self.device_ptr = 0
[docs] class NyxExternalMemoryImporter: """Imports Nyx's exported buffers into the compute API torch was built for, on the GPU Nyx renders on. Build one with :meth:`create` from the ``DeviceIdentity`` and ``EExternalMemoryHandleType`` Nyx reports, import every exported buffer with :meth:`import_buffer`, release the buffers then :meth:`close` the importer before Nyx shuts down. """
[docs] def __init__(self, api, device_index: int, handle_type: int): self._api = api self.device_index = device_index self.torch_device = torch.device("cuda", device_index) self._handle_type = int(getattr(handle_type, "value", handle_type)) self._type_code = _HANDLE_TYPE_CODES[self._handle_type] self._context = api.retain_context(device_index)
[docs] @classmethod def create(cls, device_identity, handle_type) -> "NyxExternalMemoryImporter": """Pick the compute API from the torch build and the compute device matching Nyx's ``DeviceIdentity``. Pairing compares the LUID and node mask or the PCI bus location, whichever Nyx reports. Without a match the import cannot map the memory, so creation fails. """ if not torch.cuda.is_available(): raise NyxExternalMemoryError( "torch has no GPU backend available; the Nyx interop needs a CUDA or ROCm torch build." ) api = _HipRuntime() if torch.version.hip else _CudaDriver() handle_type = int(getattr(handle_type, "value", handle_type)) if handle_type not in _HANDLE_TYPE_CODES: raise NyxExternalMemoryError( f"Unsupported exported handle type {handle_type}." ) device_index = cls._pair_device(api, device_identity) return cls(api, device_index, handle_type)
@staticmethod def _pair_device(api, device_identity) -> int: identity_type = int( getattr(device_identity.type, "value", device_identity.type) ) data = bytes(device_identity.data) for index in range(api.device_count()): if identity_type == _NYX_IDENTITY_LUID: compute_luid = api.device_luid(index) node_mask = int.from_bytes(data[8:12], "little") # A zero node mask is one the API leaves unset if ( compute_luid is not None and compute_luid[0] == data[:8] and ( not node_mask or not compute_luid[1] or compute_luid[1] == node_mask ) ): return index elif identity_type == _NYX_IDENTITY_PCI_BUS: location = tuple( int.from_bytes(data[offset : offset + 4], "little") for offset in range(0, 16, 4) ) if api.device_pci_bus(index) == location: return index raise NyxExternalMemoryError( f"NyxExternalMemoryImporter: no {api.name} device matches the GPU Nyx renders on. " "Make Nyx pick a GPU torch can see (BridgeStartupParams.pickStrategy)." ) def _push(self) -> None: self._api.push_context(self._context) def _pop(self) -> None: self._api.pop_context()
[docs] def import_buffer(self, exported) -> NyxImportedBuffer: """Import a buffer exported by Nyx (an object with ``handle``, ``allocationSize`` and ``size``). The import takes the whole dedicated allocation, as the compute APIs require, and maps the bytes Nyx reads or writes. The OS handle is released either way, the import holds its own reference. """ desc = _ExternalMemoryHandleDesc() desc.type = self._type_code if self._handle_type == _NYX_OPAQUE_FD: desc.handle.fd = int(exported.handle) else: desc.handle.win32.handle = ctypes.c_void_p(int(exported.handle)) desc.handle.win32.name = None desc.size = int(exported.allocationSize) desc.flags = _EXTERNAL_MEMORY_DEDICATED buffer_desc = _ExternalMemoryBufferDesc() buffer_desc.offset = 0 buffer_desc.size = int(exported.size) buffer_desc.flags = 0 imported = False self._push() try: memory = self._api.import_memory(desc) imported = True try: device_ptr = self._api.map_buffer(memory, buffer_desc) except NyxExternalMemoryError: self._api.destroy_memory(memory) raise finally: self._pop() _close_os_handle(int(exported.handle), self._handle_type, imported) return NyxImportedBuffer(self, memory, device_ptr, int(exported.size))
[docs] def synchronize(self) -> None: """Wait for every compute write on the device, so Nyx can read the buffers.""" torch.cuda.synchronize(self.torch_device)
[docs] def close(self) -> None: """Release the compute context. Release every imported buffer first.""" if self._context is None: return self._api.release_context(self.device_index) self._context = None