Coverage for cuda/core/_memory/_virtual_memory_resource.pyx: 89.41%

529 statements  

« prev     ^ index     » next       coverage.py v7.18.0, created at 2026-12-03 01:06 +0000

1# SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. 

2# 

3# SPDX-License-Identifier: Apache-2.0 

4  

5from __future__ import annotations 

6  

7from libc.string cimport memset 

8from libcpp.vector cimport vector 

9  

10cimport cpython 

11  

12from cuda.bindings cimport cydriver 

13from cuda.core._memory._buffer cimport ( 

14 Buffer, 

15 Buffer_check_open, 

16 Buffer_from_deviceptr_handle, 

17 MemoryResource, 

18) 

19from cuda.core._memory._ipc cimport ( 

20 IPCAllocationHandle, 

21 IPCDataForBuffer, 

22 _VirtualMemoryDescriptor, 

23 VirtualMemoryFabricBufferDescriptor, 

24 VirtualMemoryFdBufferDescriptor, 

25) 

26from cuda.core._rt cimport ( 

27 ContextHandle, 

28 DevicePtrHandle, 

29 MemAllocationHandle, 

30 StreamHandle, 

31 VaMappingHandle, 

32 VaReservationHandle, 

33 VmmRangeHandle, 

34 as_cu, 

35 create_context_bound_legacy_stream, 

36 create_mem_allocation_handle, 

37 create_va_mapping_handle, 

38 create_va_reservation_handle, 

39 create_vmm_range, 

40 deallocation_stream, 

41 deviceptr_create_vmm, 

42 get_last_error, 

43 get_primary_context, 

44 import_mem_allocation_handle, 

45 mem_allocation_is_imported, 

46 mem_allocation_size, 

47 set_deallocation_stream, 

48 va_mapping_allocation, 

49 vmm_range, 

50 vmm_range_mappings, 

51 vmm_range_total, 

52) 

53from cuda.core._stream cimport Stream, Stream_accept, Stream_handle_is_default_token, Stream_is_default_token 

54from cuda.core._utils.cuda_utils cimport HANDLE_RETURN, check_or_create_options 

55  

56import os 

57import platform 

58from dataclasses import dataclass, field, replace 

59from multiprocessing import context as _mp_context 

60from typing import TYPE_CHECKING, Iterable 

61  

62from cuda.core._device import Device, _device_from_uuid 

63from cuda.core._utils.cuda_utils import driver 

64from cuda.core.typing import ( 

65 DevicePointerType, 

66 VirtualMemoryAccessType, 

67 VirtualMemoryAllocationType, 

68 VirtualMemoryGranularityType, 

69 VirtualMemoryHandleType, 

70 VirtualMemoryLocationType, 

71) 

72  

73if TYPE_CHECKING: 

74 from cuda.core.graph import GraphBuilder 

75  

76__all__ = ["VirtualMemoryBuffer", "VirtualMemoryResource", "VirtualMemoryResourceOptions"] 

77  

78# Location types whose physical backing lives in host memory. Shared by 

79# VirtualMemoryResource.__init__ and is_host_accessible so the two cannot drift. 

80_HOST_LOCATION_TYPES = frozenset( 

81 { 

82 VirtualMemoryLocationType.HOST, 

83 VirtualMemoryLocationType.HOST_NUMA, 

84 VirtualMemoryLocationType.HOST_NUMA_CURRENT, 

85 } 

86) 

87  

88# Handle types whose exported handles cuda.core can carry to another process. 

89# POSIX file descriptors and plain fabric handles are transported on Linux. 

90# Win32 KMT handles have no transport here. 

91_IPC_HANDLE_TYPES = ( 

92 frozenset({VirtualMemoryHandleType.POSIX_FD, VirtualMemoryHandleType.FABRIC}) 

93 if platform.system() == "Linux" else frozenset() 

94) 

95  

96  

97@dataclass 

98class VirtualMemoryResourceOptions: 

99 """A configuration object for the VirtualMemoryResource 

100 Stores configuration information which tells the resource how to use the CUDA VMM APIs 

101  

102 Attributes 

103 ---------- 

104 allocation_type: :obj:`~_memory.VirtualMemoryAllocationType` | str 

105 Controls the type of allocation. Only ``"pinned"`` is supported; 

106 use :class:`ManagedMemoryResource` for managed memory. 

107 location_type: :obj:`~_memory.VirtualMemoryLocationType` | str 

108 Controls the location of the allocation. ``"host_numa"`` requires 

109 ``numa_id``. ``"host_numa_current"`` is rejected because the driver 

110 does not accept it for physical allocations. 

111 handle_type: :obj:`~_memory.VirtualMemoryHandleType` | str | None 

112 Export handle type for the physical allocation, and the switch for 

113 sharing buffers with other processes (see 

114 :attr:`VirtualMemoryResource.is_ipc_enabled`). Use ``"posix_fd"`` or 

115 ``"fabric"`` on Linux if you plan to import/export the allocation. 

116 Fabric handles work with plain ``pickle`` and pin nothing: keep the 

117 exporting buffer alive until every importer has imported it. Sharing 

118 is supported on one node; multi-node sharing is untested. Fabric needs 

119 an NVLink fabric and an accessible IMEX channel 

120 (``/dev/nvidia-caps-imex-channels/channel*``); construction raises 

121 ``RuntimeError`` if the device reports no fabric handle support. A 

122 device can report support while the allocation is refused, because 

123 the attribute does not check for an NVLink fabric and older drivers 

124 do not check for an IMEX channel; the allocation then fails with a 

125 driver error that says so. 

126 Use `None` if you don't need an exportable handle. The default is 

127 `None` on Windows and ``"posix_fd"`` otherwise. 

128 ``location_type="host"`` requires `None`. 

129 gpu_direct_rdma: bool 

130 Hint that the allocation should be GDR-capable (if supported). 

131 granularity: :obj:`~_memory.VirtualMemoryGranularityType` | str 

132 Controls granularity query and size rounding. 

133 addr_hint: int 

134 A (optional) virtual address hint to try to reserve at. Setting it to 0 lets the CUDA driver decide. 

135 addr_align: int 

136 Alignment for the VA reservation. If `None`, use the queried granularity. 

137 peers: Iterable[int] 

138 Extra device IDs that should be granted access in addition to ``device``. 

139 The options store them as a tuple. 

140 self_access: :obj:`~_memory.VirtualMemoryAccessType` | None | str 

141 Access flags for the owning device. 

142 peer_access: :obj:`~_memory.VirtualMemoryAccessType` | None | str 

143 Access flags for peers. 

144 numa_id: int | None 

145 Host NUMA node of the allocation. Required for 

146 ``location_type="host_numa"`` and rejected for every other location 

147 type. Must be >= 0; ``Device.properties.host_numa_id`` is the node 

148 closest to a device. On a system without NUMA, ``host_numa_id`` is -1 

149 and the driver expects ``numa_id=0``. 

150 """ 

151  

152 allocation_type: VirtualMemoryAllocationType = VirtualMemoryAllocationType.PINNED 

153 location_type: VirtualMemoryLocationType = VirtualMemoryLocationType.DEVICE 

154 handle_type: VirtualMemoryHandleType | str | None = field( 

155 default_factory=lambda: None if platform.system() == "Windows" else VirtualMemoryHandleType.POSIX_FD 

156 ) 

157 granularity: VirtualMemoryGranularityType = VirtualMemoryGranularityType.RECOMMENDED 

158 gpu_direct_rdma: bool = False 

159 addr_hint: int | None = 0 

160 addr_align: int | None = None 

161 peers: Iterable[int] = field(default_factory=tuple) 

162 self_access: VirtualMemoryAccessType = VirtualMemoryAccessType.READ_WRITE 

163 peer_access: VirtualMemoryAccessType = VirtualMemoryAccessType.READ_WRITE 

164 numa_id: int | None = None 

165  

166 _a = driver.CUmemAccess_flags 

167 _access_flags = { # noqa: RUF012 

168 VirtualMemoryAccessType.READ_WRITE: _a.CU_MEM_ACCESS_FLAGS_PROT_READWRITE, 

169 VirtualMemoryAccessType.READ: _a.CU_MEM_ACCESS_FLAGS_PROT_READ, 

170 None: 0, 

171 } 

172 _h = driver.CUmemAllocationHandleType 

173 _handle_types = { # noqa: RUF012 

174 None: _h.CU_MEM_HANDLE_TYPE_NONE, 

175 VirtualMemoryHandleType.POSIX_FD: _h.CU_MEM_HANDLE_TYPE_POSIX_FILE_DESCRIPTOR, 

176 VirtualMemoryHandleType.WIN32_KMT: _h.CU_MEM_HANDLE_TYPE_WIN32_KMT, 

177 VirtualMemoryHandleType.FABRIC: _h.CU_MEM_HANDLE_TYPE_FABRIC, 

178 } 

179 _g = driver.CUmemAllocationGranularity_flags 

180 _granularity = { # noqa: RUF012 

181 VirtualMemoryGranularityType.RECOMMENDED: _g.CU_MEM_ALLOC_GRANULARITY_RECOMMENDED, 

182 VirtualMemoryGranularityType.MINIMUM: _g.CU_MEM_ALLOC_GRANULARITY_MINIMUM, 

183 } 

184 _l = driver.CUmemLocationType 

185 _location_type = { # noqa: RUF012 

186 VirtualMemoryLocationType.DEVICE: _l.CU_MEM_LOCATION_TYPE_DEVICE, 

187 VirtualMemoryLocationType.HOST: _l.CU_MEM_LOCATION_TYPE_HOST, 

188 VirtualMemoryLocationType.HOST_NUMA: _l.CU_MEM_LOCATION_TYPE_HOST_NUMA, 

189 VirtualMemoryLocationType.HOST_NUMA_CURRENT: _l.CU_MEM_LOCATION_TYPE_HOST_NUMA_CURRENT, 

190 } 

191 _t = driver.CUmemAllocationType 

192 # cuMemCreate only supports PINNED, even on CUDA 13 builds with a MANAGED enum member. 

193 _allocation_type = {VirtualMemoryAllocationType.PINNED: _t.CU_MEM_ALLOCATION_TYPE_PINNED} # noqa: RUF012 

194  

195 def __post_init__(self) -> None: 

196 self._allocation_type_to_driver(self.allocation_type) 2: q ; Vbhb1 ib3 jbM kblbV mb4 nb5 obW pbX qbrbWbsbY tbubXbvbZ wbxbYbybQ zb0 AbR BbS CbT Dbz A N EbO FbU Gb~ ` UbC e c | } g h D b E H i k j d a ! f B I l gbHbcbdbLbIbMbbbF G J K = / ) ? r s y 2 , - o p [ ] + v w . m % ' abP L t u ^ x ebfb* $ Tb( ObJb# QbPbSbRbZb0b1b_ @ NbKb6 n

197 # Allocation and pickling each read the peers, so a one-shot iterable 

198 # such as a generator must not reach them. 

199 self.peers = tuple(int(peer) for peer in self.peers) 2: q ; Vbhb1 ib3 jbM kblbV mb4 nb5 obW pbX qbrbWbsbY tbubXbvbZ wbxbYbybQ zb0 AbR BbS CbT Dbz A N EbO FbU Gb~ ` UbC e c | } g h D b E H i k j d a ! f B I l gbHbcbdbLbIbMbbbF G J K = / ) ? r s y 2 , - o p [ ] + v w . m % ' abP L t u ^ x ebfb* $ Tb( ObJb# QbPbSbRbZb0b1b_ @ NbKb6 n

200  

201 @staticmethod 

202 def _access_to_flags(spec: VirtualMemoryAccessType | None) -> int: 

203 flags = VirtualMemoryResourceOptions._access_flags.get(spec) 2: q ; 1 3 M V 4 5 W X 7 Y 8 Z 9 Q 0 R S T z A N O U ` C e c g h D b E H i k j d a ! f B I l F G J K = / ) ? r s y 2 , - o p [ ] + v w . m % ' P L t u ^ x * $ ( # 3b_ @ 6 n

204 if flags is None: 2: q ; 1 3 M V 4 5 W X 7 Y 8 Z 9 Q 0 R S T z A N O U ` C e c g h D b E H i k j d a ! f B I l F G J K = / ) ? r s y 2 , - o p [ ] + v w . m % ' P L t u ^ x * $ ( # 3b_ @ 6 n

205 raise ValueError(f"Unknown access spec: {spec!r}") 23b

206 return flags # type: ignore[no-any-return] 1:q;13MV45WX7Y8Z9Q0RSTzANOU`CecghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#_@6n

207  

208 @staticmethod 

209 def _allocation_type_to_driver(spec: VirtualMemoryAllocationType) -> int: 

210 alloc_type = VirtualMemoryResourceOptions._allocation_type.get(spec) 2: q ; Vbhb1 ib3 jbM kblbV mb4 nb5 obW pbX qb7 rbWbsbY tb8 ubXbvbZ wb9 xbYbybQ zb0 AbR BbS CbT Dbz A N EbO FbU Gb~ ` UbC e c | } g h D b E H i k j d a ! f B I l gbHbcbdbLbIbMbbbF G J K = / ) ? r s y 2 , - o p [ ] + v w . m % ' abP L t u ^ x ebfb* $ Tb( ObJb# QbPbSbRbZb0b4b1b_ @ NbKb6 n

211 if alloc_type is None: 2: q ; Vbhb1 ib3 jbM kblbV mb4 nb5 obW pbX qb7 rbWbsbY tb8 ubXbvbZ wb9 xbYbybQ zb0 AbR BbS CbT Dbz A N EbO FbU Gb~ ` UbC e c | } g h D b E H i k j d a ! f B I l gbHbcbdbLbIbMbbbF G J K = / ) ? r s y 2 , - o p [ ] + v w . m % ' abP L t u ^ x ebfb* $ Tb( ObJb# QbPbSbRbZb0b4b1b_ @ NbKb6 n

212 raise ValueError(f"Unsupported allocation_type: {spec!r}") 2Zb0b4b

213 return alloc_type # type: ignore[no-any-return] 2: q ; Vbhb1 ib3 jbM kblbV mb4 nb5 obW pbX qb7 rbWbsbY tb8 ubXbvbZ wb9 xbYbybQ zb0 AbR BbS CbT Dbz A N EbO FbU Gb~ ` UbC e c | } g h D b E H i k j d a ! f B I l gbHbcbdbLbIbMbbbF G J K = / ) ? r s y 2 , - o p [ ] + v w . m % ' abP L t u ^ x ebfb* $ Tb( ObJb# QbPbSbRbZb0b1b_ @ NbKb6 n

214  

215 @staticmethod 

216 def _location_type_to_driver(spec: VirtualMemoryLocationType) -> int: 

217 loc_type = VirtualMemoryResourceOptions._location_type.get(spec) 2: q ; 1 3 M V 4 5 W X 7 Y 8 Z 9 Q 0 R S T z A N O U ` C e c g h D b E H i k j d a ! f B I l F G J K = / ) ? r s y 2 , - o p [ ] + v w . m % ' P L t u ^ x * $ ( # 5b_ @ 6 n

218 if loc_type is None: 2: q ; 1 3 M V 4 5 W X 7 Y 8 Z 9 Q 0 R S T z A N O U ` C e c g h D b E H i k j d a ! f B I l F G J K = / ) ? r s y 2 , - o p [ ] + v w . m % ' P L t u ^ x * $ ( # 5b_ @ 6 n

219 raise ValueError(f"Unsupported location_type: {spec!r}") 25b

220 return loc_type # type: ignore[no-any-return] 1:q;13MV45WX7Y8Z9Q0RSTzANOU`CecghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#_@6n

221  

222 @staticmethod 

223 def _handle_type_to_driver(spec: VirtualMemoryHandleType | str | None) -> int: 

224 if spec == "win32": 2: q ; 1 3 M V 4 5 W X 7 Y 8 Z 9 Q 0 R S T z A N O U ~ ` C e c | } g h D b E H i k j d a ! f B I l F G J K = / ) ? r s y 2 , - o p [ ] + v w . m % ' abP L t u ^ x * $ ( # 7b2b_ @ 6 n

225 raise NotImplementedError("win32 is currently not supported, please reach out to the CUDA Python team") 27b

226 handle_type = VirtualMemoryResourceOptions._handle_types.get(spec) 2: q ; 1 3 M V 4 5 W X 7 Y 8 Z 9 Q 0 R S T z A N O U ~ ` C e c | } g h D b E H i k j d a ! f B I l F G J K = / ) ? r s y 2 , - o p [ ] + v w . m % ' abP L t u ^ x * $ ( # 2b_ @ 6 n

227 if handle_type is None: 2: q ; 1 3 M V 4 5 W X 7 Y 8 Z 9 Q 0 R S T z A N O U ~ ` C e c | } g h D b E H i k j d a ! f B I l F G J K = / ) ? r s y 2 , - o p [ ] + v w . m % ' abP L t u ^ x * $ ( # 2b_ @ 6 n

228 raise ValueError(f"Unsupported handle_type: {spec!r}") 22b

229 return handle_type # type: ignore[no-any-return] 2: q ; 1 3 M V 4 5 W X 7 Y 8 Z 9 Q 0 R S T z A N O U ~ ` C e c | } g h D b E H i k j d a ! f B I l F G J K = / ) ? r s y 2 , - o p [ ] + v w . m % ' abP L t u ^ x * $ ( # _ @ 6 n

230  

231 @staticmethod 

232 def _granularity_to_driver(spec: VirtualMemoryGranularityType) -> int: 

233 granularity = VirtualMemoryResourceOptions._granularity.get(spec) 2: q ; 1 3 M V 4 5 W X 7 Y 8 Z 9 Q 0 R S T z A N O U ` C e c g h D b E H i k j d a ! f B I l F G J K = / ) ? r s y 2 , - o p [ ] + v w . m % ' P L t u ^ x * $ ( # 6b_ @ 6 n

234 if granularity is None: 2: q ; 1 3 M V 4 5 W X 7 Y 8 Z 9 Q 0 R S T z A N O U ` C e c g h D b E H i k j d a ! f B I l F G J K = / ) ? r s y 2 , - o p [ ] + v w . m % ' P L t u ^ x * $ ( # 6b_ @ 6 n

235 raise ValueError(f"Unsupported granularity: {spec!r}") 26b

236 return granularity # type: ignore[no-any-return] 1:q;13MV45WX7Y8Z9Q0RSTzANOU`CecghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#_@6n

237  

238  

239cdef inline size_t _align_up(size_t size, size_t gran) except? 0: 

240 """Round ``size`` up to a multiple of ``gran``. 

241  

242 Raises ``OverflowError`` instead of wrapping when the rounded size does not 

243 fit in ``size_t``. 

244 """ 

245 if size > <size_t>-1 - (gran - 1): 1:q;13MV45WX7Y8Z9Q0RSTzANOU`CecghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#_@6n

246 raise OverflowError(f"size {size} rounded up to the {gran}-byte granularity does not fit in size_t") 16

247 return (size + gran - 1) // gran * gran 1:q;13MV45WX7Y8Z9Q0RSTzANOU`CecghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#_@6n

248  

249  

250cdef bint _stream_is_capturing(cydriver.CUstream s) except -1: 

251 cdef cydriver.CUstreamCaptureStatus cap_status 

252 IF CUDA_CORE_BUILD_MAJOR >= 13: 

253 HANDLE_RETURN(cydriver.cuStreamGetCaptureInfo(s, &cap_status, NULL, NULL, NULL, NULL, NULL)) 1V|=2[]+vw.

254 ELSE: 

255 HANDLE_RETURN(cydriver.cuStreamGetCaptureInfo(s, &cap_status, NULL, NULL, NULL, NULL)) 

256 return cap_status == cydriver.CU_STREAM_CAPTURE_STATUS_ACTIVE 1V|=2[]+vw.

257  

258  

259cdef int _raise_last_error() except -1: 

260 """Raise the status a handle factory recorded when it returned empty.""" 

261 HANDLE_RETURN(get_last_error()) 1ec/)P

262 raise RuntimeError( 

263 "internal cuda.core error, please report: a virtual memory handle factory " 

264 "returned an empty handle without recording a CUDA error" 

265 ) 

266  

267  

268cdef int _raise_last_error_noting(str detail) except -1: 

269 """Raise the status a handle factory recorded, with ``detail`` attached as a note.""" 

270 try: 1ec

271 _raise_last_error() 1ec

272 except Exception as exc: 1ec

273 exc.add_note(detail) 1ec

274 raise 1ec

275 return 0 

276  

277  

278cdef int _raise_allocation_error( 

279 cydriver.CUresult status, cydriver.CUmemAllocationHandleType requested_handle_types 

280) except -1: 

281 """Raise a physical-allocation failure, noting possible fabric configuration errors.""" 

282 if (requested_handle_types == cydriver.CU_MEM_HANDLE_TYPE_FABRIC 1`

283 and status in (cydriver.CUDA_ERROR_NOT_PERMITTED, 1`

284 cydriver.CUDA_ERROR_NOT_SUPPORTED, 1`

285 cydriver.CUDA_ERROR_INVALID_VALUE)): 

286 _check_noting( 1`

287 status, 

288 "while creating a physical allocation with a fabric handle; fabric handles need an NVLink fabric " 

289 "and an accessible IMEX channel, and a device can report support while the allocation is refused " 

290 "(the attribute does not check for an NVLink fabric, and older drivers do not check for an IMEX " 

291 "channel)" 

292 ) 

293 HANDLE_RETURN(status) 

294 raise RuntimeError( 

295 "internal cuda.core error, please report: a physical allocation factory " 

296 "returned an empty handle without recording a CUDA error" 

297 ) 

298  

299  

300cdef int _check_noting(cydriver.CUresult status, str detail) except -1: 

301 """``HANDLE_RETURN(status)``, with ``detail`` attached to the raised error as a note.""" 

302 if status == cydriver.CUDA_SUCCESS: 113MV45WX7Y8Z9Q0RSTzANOU`CecghDbEHikjdafBIlFGJK

303 return 0 113MV45WX7Y8Z9Q0RSTzANOUCecghDbEHikjdafBIlFGJK

304 try: 1`

305 HANDLE_RETURN(status) 1`

306 except Exception as exc: 1`

307 exc.add_note(detail) 1`

308 raise 1`

309 return 0 

310  

311  

312cdef str _describe_location(cydriver.CUmemLocation loc): 

313 """Name a driver memory location for an error message.""" 

314 if loc.type == cydriver.CU_MEM_LOCATION_TYPE_DEVICE: 

315 return f"device {loc.id}" 

316 if loc.type == cydriver.CU_MEM_LOCATION_TYPE_HOST: 

317 return "host memory" 

318 if loc.type == cydriver.CU_MEM_LOCATION_TYPE_HOST_NUMA: 

319 return f"host NUMA node {loc.id}" 

320 if loc.type == cydriver.CU_MEM_LOCATION_TYPE_HOST_NUMA_CURRENT: 

321 return "the current host NUMA node" 

322 return f"location type {<int>loc.type}" 

323  

324  

325cdef class VirtualMemoryBuffer(Buffer): 

326 """A :class:`Buffer` returned by :class:`VirtualMemoryResource`. 

327  

328 The buffer owns its address reservations, physical allocations and 

329 mappings through its device pointer handle; closing it is the only way 

330 to release them. A buffer returned by 

331 :meth:`VirtualMemoryResource.modify_allocation` aliases the buffer it 

332 was grown from: the two share their physical memory, and that memory is 

333 freed when the last buffer that maps it closes. 

334 """ 

335  

336 @property 

337 def ipc_descriptor(self) -> VirtualMemoryFdBufferDescriptor | VirtualMemoryFabricBufferDescriptor: 

338 """A new descriptor for sharing this buffer with other processes. 

339  

340 The descriptor type follows the resource's ``handle_type``. Fabric 

341 descriptors carry plain bytes and pin nothing: keep the exporting 

342 buffer alive until every importer has imported it. Plain ``pickle`` 

343 works for fabric descriptors and buffers. 

344  

345 For ``"posix_fd"``, every access exports the physical allocations 

346 again and returns a new descriptor that owns one file descriptor per 

347 allocation; the file descriptors close when the descriptor is 

348 released. Keep the descriptor in a variable while you use its 

349 ``fds``: the numbers from ``buf.ipc_descriptor.fds`` alone may 

350 already be closed. A descriptor pins the physical memory while it 

351 exists, in every process that holds one, and nothing else does: the 

352 buffer itself keeps no descriptor, so it pins nothing beyond its own 

353 mapping. 

354 Pickling the buffer through ``multiprocessing`` builds a transient 

355 descriptor, so the sender holds no file descriptors between sends; 

356 a buffer passed as a ``Process`` argument is the exception, because 

357 the child receives the file descriptors when it is spawned, after 

358 pickling, so that descriptor lives until the ``Process`` object is 

359 released. Requires a resource whose ``handle_type`` can be shared; see 

360 :attr:`VirtualMemoryResource.is_ipc_enabled`. Import with 

361 :meth:`Buffer.from_ipc_descriptor` and a 

362 :class:`VirtualMemoryResource` of the receiving process, or send the 

363 buffer itself. 

364  

365 Raises 

366 ------ 

367 RuntimeError 

368 If the resource is not IPC-enabled, or the buffer contains memory 

369 imported from another process (an import, or a buffer 

370 :meth:`VirtualMemoryResource.modify_allocation` derived from 

371 one): such memory cannot be exported again. Forward the descriptor 

372 it was imported from, or copy the data into a buffer this process 

373 allocated. The check happens before any driver call. 

374 """ 

375 Buffer_check_open(self) 13M45W7890NO~ec|}ghbikjdafBIlJK

376 return _export_ipc_descriptor(self) 13M45W7890NO~ec|}ghbikjdafBIlJK

377  

378 def __reduce__(self) -> tuple[object, ...]: 

379 # Unpickling performs a live import from the descriptor; only deserialize 

380 # Buffers from a trusted principal. Must not serialize the parent's stream. 

381 Buffer_check_open(self) 11VXYZQRSTzANOUCDEHafBFG

382 desc = _export_ipc_descriptor(self) 11VXYZQRSTzANOUCDEHafBFG

383 if isinstance(desc, VirtualMemoryFabricBufferDescriptor): 11VXYZQRSTzANOUCDEHBFG

384 return Buffer._reduce_helper, (self.memory_resource, desc) 

385 popen = _mp_context.get_spawning_popen() 11VXYZQRSTzANOUCDEHBFG

386 if popen is not None: 11VXYZQRSTzANOUCDEHBFG

387 # A Queue, Pipe, or Pool duplicates the file descriptors while this 

388 # transient descriptor is alive. A spawned Process does not: it 

389 # records their numbers now and hands them to the child when it is 

390 # created, after pickling has finished. Keep the descriptor on the 

391 # Popen until then; the Popen dies with the Process object. 

392 vars(popen).setdefault("_cuda_core_descriptors_until_spawned", []).append(desc) 1XYZzANCDE

393 return Buffer._reduce_helper, (self.memory_resource, desc) 11VXYZQRSTzANOUCDEHBFG

394  

395 def close(self, stream: Stream | GraphBuilder | None = None) -> None: 

396 """Release this buffer's share of its address range. 

397  

398 Each mapping, reservation and physical allocation goes away when the 

399 last buffer that holds it closes. Virtual memory is unmapped 

400 synchronously, so this call waits for the work queued on the 

401 deallocation stream before it releases this buffer's share; a buffer 

402 released by the garbage collector waits at that point instead. The 

403 unmap cannot be captured. When the stream this close uses, given or recorded, is not 

404 a default stream and is capturing, the call raises and leaves the 

405 buffer open. A default stream is checked when the range is released 

406 instead: if synchronizing it would disturb a capture in its context, 

407 the release reports a :class:`CUDAWarning` and unmaps without 

408 synchronizing that stream. 

409  

410 Parameters 

411 ---------- 

412 stream : :obj:`~_stream.Stream` | :obj:`~graph.GraphBuilder`, optional 

413 If given, replaces the recorded deallocation stream, as for 

414 :meth:`Buffer.close`. 

415 """ 

416 cdef Stream s 

417 cdef StreamHandle h 

418 if not self._h_ptr: 1:q;VWQ0RSTzANOU~Cec|}ghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#@6n

419 return 1zA|}=

420 if stream is not None: 1:q;VWQ0RSTzANOU~Cec|}ghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#@6n

421 s = Stream_accept(stream) 1W+

422 h = s._h_stream 1W+

423 else: 

424 # Empty when no stream was recorded (host-located memory). 

425 h = deallocation_stream(self._h_ptr) 1:q;VQ0RSTzANOU~Cec|}ghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#@6n

426 # Default-stream tokens are checked by the range deleter under their 

427 # bound context; a real stream can be checked here and refused. 

428 if h and not Stream_handle_is_default_token(as_cu(h)) and _stream_is_capturing(as_cu(h)): 1:q;VWQ0RSTzANOU~Cec|}ghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#@6n

429 raise RuntimeError( 1|+.

430 "cannot close a VirtualMemoryResource buffer on a capturing stream: " 

431 "virtual memory deallocation is synchronous and cannot be captured" 

432 ) 

433 Buffer.close(self, stream) 1:q;VWQ0RSTzANOU~Cec|}ghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#@6n

434  

435  

436cdef class VirtualMemoryResource(MemoryResource): 

437 """Create a device memory resource that uses the CUDA VMM APIs to allocate memory. 

438  

439 Parameters 

440 ---------- 

441 device_id : Device | int 

442 Device for which a memory resource is constructed. 

443  

444 config : VirtualMemoryResourceOptions, optional 

445 A configuration object for the VirtualMemoryResource 

446  

447  

448 Warning 

449 ------- 

450 This is a low-level API that is provided only for convenience. Make sure you fully understand 

451 how CUDA Virtual Memory Management works before using this. Other MemoryResource subclasses 

452 in cuda.core should already meet the common needs. 

453  

454 A shared buffer's descriptor comes from the exporting process and is not trusted: 

455 :meth:`Buffer.from_ipc_descriptor` checks what it can, and the driver rejects a size that 

456 does not match the exported allocation. Unpickling a shared buffer performs a live import, 

457 so unpickle buffers only from a trusted principal. A POSIX fd descriptor pins the physical 

458 memory while it exists; release it when the receiver has imported it. Fabric descriptors 

459 pin nothing; keep the exporting buffer alive until every importer has imported it. 

460  

461 Notes 

462 ----- 

463 Every buffer this resource returns is a :class:`VirtualMemoryBuffer` that 

464 owns its address reservations, physical allocations and mappings; closing 

465 the buffer releases them. :meth:`deallocate` is not involved in that path. 

466  

467 Virtual memory is unmapped synchronously, so closing a buffer waits for 

468 the work queued on its deallocation stream. A buffer released by the 

469 garbage collector waits at that point instead. To control when the wait 

470 happens, close the buffer explicitly or record an idle stream with 

471 :meth:`Buffer.set_deallocation_stream`. 

472  

473 Buffers can be shared with other processes when ``config.handle_type`` 

474 is ``"posix_fd"`` or ``"fabric"`` on Linux; 

475 ``handle_type`` is the switch and :attr:`is_ipc_enabled` the query. The 

476 rules that follow describe POSIX file descriptors. 

477 :attr:`Buffer.ipc_descriptor` exports the physical allocations that back 

478 a buffer, one file descriptor each, into a new descriptor on every 

479 access; :meth:`Buffer.from_ipc_descriptor` imports a descriptor with a 

480 ``VirtualMemoryResource`` of the receiving process for the device that 

481 owns the memory; and a buffer sent through ``multiprocessing`` does both. 

482 A pickled resource names its device and its ``peers`` by UUID, and the 

483 receiving process rebuilds it for the devices with those UUIDs, whatever 

484 their ordinals are there; it raises ``RuntimeError`` if one of the devices 

485 is not visible. Plain ``pickle`` cannot carry the file descriptors; a 

486 process with its own file descriptor passing sends the descriptor's 

487 ``fds``, ``sizes``, and ``size`` and rebuilds it with 

488 ``VirtualMemoryFdBufferDescriptor.from_fds()``. The importing resource 

489 maps the memory for its device and the devices in its ``peers`` option, 

490 with its own access options. A descriptor pins the physical memory while 

491 it exists, in every process that holds one, and nothing else does. 

492 Fabric descriptors carry one opaque 64-byte handle per allocation and work 

493 with plain ``pickle``; they pin nothing, so the exporter must keep the 

494 buffer alive until every importer has imported it. Rebuild handles sent 

495 through a transport of your own with 

496 ``VirtualMemoryFabricBufferDescriptor.from_handles()``. Fabric sharing is 

497 supported on one node; multi-node sharing is untested. It requires a device 

498 on an NVLink fabric and an accessible IMEX channel 

499 (``/dev/nvidia-caps-imex-channels/channel*``); construction raises 

500 ``RuntimeError`` when the device reports no fabric handle support. A device 

501 can report support while the allocation is refused, because the attribute 

502 does not check for an NVLink fabric and older drivers do not check for an 

503 IMEX channel; the allocation then fails with a driver error that says so. 

504 Fabric-handle sharing was validated on NVIDIA internal hardware and is not 

505 covered by the project's CI in this release. 

506 A buffer that contains imported memory (an import, or anything 

507 :meth:`modify_allocation` derived from one) cannot be exported again; 

508 forward the descriptor it came from, or copy into a buffer you own. 

509 """ 

510  

511 cdef: 

512 readonly object device 

513 readonly object config 

514 object __weakref__ 

515  

516 def __init__(self, device_id: Device | int, config: VirtualMemoryResourceOptions | None = None) -> None: 

517 self.device = Device(device_id) 2: q ; hbibjbM kblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbz A EbFbGb~ ` UbC e c | } g h D b E H i k j d a ! f B I l gbHbcbdbLbIbMbbbF G J K = / ) ? r s y 2 , - o p [ ] + v w . m % ' abP L t u ^ x ebfb* $ Tb( ObJb# QbPbSbRb_ @ NbKb6 n

518 self.config = check_or_create_options( 2: q ; hbibjbM kblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbz A EbFbGb~ ` UbC e c | } g h D b E H i k j d a ! f B I l gbHbcbdbLbIbMbbbF G J K = / ) ? r s y 2 , - o p [ ] + v w . m % ' abP L t u ^ x ebfb* $ Tb( ObJb# QbPbSbRb_ @ NbKb6 n

519 VirtualMemoryResourceOptions, config, "VirtualMemoryResource options", keep_none=False 2: q ; hbibjbM kblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbz A EbFbGb~ ` UbC e c | } g h D b E H i k j d a ! f B I l gbHbcbdbLbIbMbbbF G J K = / ) ? r s y 2 , - o p [ ] + v w . m % ' abP L t u ^ x ebfb* $ Tb( ObJb# QbPbSbRb_ @ NbKb6 n

520 ) 

521 if self.config.location_type in _HOST_LOCATION_TYPES: 2: q ; hbibjbM kblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbz A EbFbGb~ ` UbC e c | } g h D b E H i k j d a ! f B I l gbHbcbdbLbIbMbbbF G J K = / ) ? r s y 2 , - o p [ ] + v w . m % ' abP L t u ^ x ebfb* $ Tb( ObJb# QbPbSbRb_ @ NbKb6 n

522 self.device = None 2Hbcbdb^ x ebfb* $ TbPbSbRbKb

523 if self.device is not None and not self.device.properties.virtual_memory_management_supported: 2: q ; hbibjbM kblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbz A EbFbGb~ ` UbC e c | } g h D b E H i k j d a ! f B I l gbHbcbdbLbIbMbbbF G J K = / ) ? r s y 2 , - o p [ ] + v w . m % ' abP L t u ^ x ebfb* $ Tb( ObJb# QbPbSbRb_ @ NbKb6 n

524 raise RuntimeError("VirtualMemoryResource requires CUDA VMM API support") 

525 if (self.config.handle_type == VirtualMemoryHandleType.FABRIC 2: q ; hbibjbM kblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbz A EbFbGb~ ` UbC e c | } g h D b E H i k j d a ! f B I l gbHbcbdbLbIbMbbbF G J K = / ) ? r s y 2 , - o p [ ] + v w . m % ' abP L t u ^ x ebfb* $ Tb( ObJb# QbPbSbRb_ @ NbKb6 n

526 and self.device is not None and not self.device.properties.handle_type_fabric_supported): 2~ ` Ubgbcb

527 raise RuntimeError( 2Ub

528 "fabric handles need a device on an NVLink fabric and an accessible IMEX channel " 2Ub

529 "(/dev/nvidia-caps-imex-channels/channel*); " 

530 f"device {self.device.device_id} reports no fabric handle support" 2Ub

531 ) 

532 self._check_config(self.config) 2: q ; hbibjbM kblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbz A EbFbGb~ ` C e c | } g h D b E H i k j d a ! f B I l gbHbcbdbLbIbMbbbF G J K = / ) ? r s y 2 , - o p [ ] + v w . m % ' abP L t u ^ x ebfb* $ Tb( ObJb# QbPbSbRb_ @ NbKb6 n

533  

534 def __reduce__(self) -> tuple[object, ...]: 

535 # The resource holds no driver object that other processes must share; 

536 # the receiving process rebuilds an equivalent one from the device and 

537 # the options. This is what lets a Buffer pickle as (resource, descriptor). 

538 # Device ordinals are per process, so the owning device and the peers 

539 # travel by UUID and the receiver maps them to its own devices. 

540 owner_uuid = self.device.uuid if self.device is not None else None 2Vb1 3 M V 4 5 W X WbY XbZ YbQ 0 R S T z A N O U C D E H B bbF G J K

541 peer_uuids = tuple(Device(peer).uuid for peer in self.config.peers) 2Vb1 3 M V 4 5 W X WbY XbZ YbQ 0 R S T z A N O U C D E H B bbF G J K

542 return _reconstruct_virtual_memory_resource, ( 2Vb1 3 M V 4 5 W X WbY XbZ YbQ 0 R S T z A N O U C D E H B bbF G J K

543 type(self), owner_uuid, peer_uuids, replace(self.config, peers=())) 2Vb1 3 M V 4 5 W X WbY XbZ YbQ 0 R S T z A N O U C D E H B bbF G J K

544  

545 cdef int _check_config(self, object cfg) except -1: 

546 """Reject options the driver would reject, before any driver call. 

547  

548 Shared by ``__init__`` and ``modify_allocation``, so a per-call 

549 configuration is held to the same rules as the resource's own. 

550 """ 

551 VirtualMemoryResourceOptions._allocation_type_to_driver(cfg.allocation_type) 2: q ; hbibjbM kblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbz A EbFbGb~ ` C e c | } g h D b E H i k j d a ! f B I l gbHbcbdbLbIbMbbbF G J K = / ) ? r s y 2 , - o p [ ] + v w . m % ' abP L t u ^ x ebfb* $ Tb( ObJb# QbPbSbRb_ @ NbKb6 n

552 if cfg.location_type != self.config.location_type: 2: q ; hbibjbM kblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbz A EbFbGb~ ` C e c | } g h D b E H i k j d a ! f B I l gbHbcbdbLbIbMbbbF G J K = / ) ? r s y 2 , - o p [ ] + v w . m % ' abP L t u ^ x ebfb* $ Tb( ObJb# QbPbSbRb_ @ NbKb6 n

553 raise ValueError( 1#

554 f"config.location_type {str(cfg.location_type)!r} does not match the resource's " 1#

555 f"{str(self.config.location_type)!r}; the location of a buffer cannot change" 1#

556 ) 

557 if cfg.numa_id != self.config.numa_id: 2: q ; hbibjbM kblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbz A EbFbGb~ ` C e c | } g h D b E H i k j d a ! f B I l gbHbcbdbLbIbMbbbF G J K = / ) ? r s y 2 , - o p [ ] + v w . m % ' abP L t u ^ x ebfb* $ Tb( ObJb# QbPbSbRb_ @ NbKb6 n

558 raise ValueError( 1$

559 f"config.numa_id {cfg.numa_id!r} does not match the resource's " 1$

560 f"{self.config.numa_id!r}; the location of a buffer cannot change" 1$

561 ) 

562 if cfg.location_type == VirtualMemoryLocationType.HOST_NUMA_CURRENT: 2: q ; hbibjbM kblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbz A EbFbGb~ ` C e c | } g h D b E H i k j d a ! f B I l gbHbcbdbLbIbMbbbF G J K = / ) ? r s y 2 , - o p [ ] + v w . m % ' abP L t u ^ x ebfb* $ Tb( ObJb# QbPbSbRb_ @ NbKb6 n

563 raise ValueError( 2Tb

564 'location_type="host_numa_current" is not supported: the driver does not accept it ' 

565 'for physical allocations; use location_type="host_numa" with numa_id' 

566 ) 

567 if cfg.location_type == VirtualMemoryLocationType.HOST_NUMA: 2: q ; hbibjbM kblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbz A EbFbGb~ ` C e c | } g h D b E H i k j d a ! f B I l gbHbcbdbLbIbMbbbF G J K = / ) ? r s y 2 , - o p [ ] + v w . m % ' abP L t u ^ x ebfb* $ ( ObJb# QbPbSbRb_ @ NbKb6 n

568 if cfg.numa_id is None: 2cbdbfb$ SbRb

569 raise ValueError( 2Sb

570 'location_type="host_numa" requires numa_id; pass numa_id=<host NUMA node id>, ' 

571 "e.g. device.properties.host_numa_id" 

572 ) 

573 if cfg.numa_id < 0: 2cbdbfb$ Rb

574 raise ValueError(f"numa_id must be >= 0, got {cfg.numa_id}") 2Rb

575 elif cfg.numa_id is not None: 2: q ; hbibjbM kblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbz A EbFbGb~ ` C e c | } g h D b E H i k j d a ! f B I l gbHbLbIbMbbbF G J K = / ) ? r s y 2 , - o p [ ] + v w . m % ' abP L t u ^ x eb* ( ObJb# QbPb_ @ NbKb6 n

576 raise ValueError( 2QbPb

577 'numa_id is only valid with location_type="host_numa", ' 2QbPb

578 f"got location_type={str(cfg.location_type)!r}" 2QbPb

579 ) 

580 # The driver rejects an exportable handle type for HOST memory only; 

581 # the NUMA location types may carry one. 

582 if cfg.location_type == VirtualMemoryLocationType.HOST and cfg.handle_type is not None: 2: q ; hbibjbM kblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbz A EbFbGb~ ` C e c | } g h D b E H i k j d a ! f B I l gbHbcbdbLbIbMbbbF G J K = / ) ? r s y 2 , - o p [ ] + v w . m % ' abP L t u ^ x ebfb* $ ( ObJb# _ @ NbKb6 n

583 raise ValueError( 2eb*

584 'virtual memory with location_type="host" cannot have an exportable handle type; ' 

585 "pass handle_type=None" 

586 ) 

587 # The handle type is part of the resource's sharing contract, like the 

588 # location: every chunk of a buffer must be exportable the same way. 

589 if cfg.handle_type != self.config.handle_type: 2: q ; hbibjbM kblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbz A EbFbGb~ ` C e c | } g h D b E H i k j d a ! f B I l gbHbcbdbLbIbMbbbF G J K = / ) ? r s y 2 , - o p [ ] + v w . m % ' abP L t u ^ x ebfb* $ ( ObJb# _ @ NbKb6 n

590 raise ValueError( 1!

591 f"config.handle_type {str(cfg.handle_type)!r} does not match the resource's " 1!

592 f"{str(self.config.handle_type)!r}; the handle type of a buffer's chunks cannot change" 1!

593 ) 

594 if cfg.gpu_direct_rdma and self.device is not None and not self.device.properties.gpu_direct_rdma_supported: 2: q ; hbibjbM kblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbz A EbFbGb~ ` C e c | } g h D b E H i k j d a ! f B I l gbHbcbdbLbIbMbbbF G J K = / ) ? r s y 2 , - o p [ ] + v w . m % ' abP L t u ^ x ebfb* $ ( ObJb# _ @ NbKb6 n

595 raise RuntimeError("GPU Direct RDMA is not supported on this device") 

596 return 0 2: q ; hbibjbM kblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbz A EbFbGb~ ` C e c | } g h D b E H i k j d a ! f B I l gbHbcbdbLbIbMbbbF G J K = / ) ? r s y 2 , - o p [ ] + v w . m % ' abP L t u ^ x ebfb* $ ( ObJb# _ @ NbKb6 n

597  

598 cdef int _fill_prop(self, object cfg, cydriver.CUmemAllocationProp* prop) except -1: 

599 # The location comes from the resource; the rest may come from a 

600 # per-call configuration. 

601 cdef int alloc_type = int(VirtualMemoryResourceOptions._allocation_type_to_driver(cfg.allocation_type)) 1:q;13MV45WX7Y8Z9Q0RSTzANOU`CecghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#_@6n

602 cdef int loc_type = int(VirtualMemoryResourceOptions._location_type_to_driver(self.config.location_type)) 1:q;13MV45WX7Y8Z9Q0RSTzANOU`CecghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#_@6n

603 cdef int handle_type = int(VirtualMemoryResourceOptions._handle_type_to_driver(cfg.handle_type)) 1:q;13MV45WX7Y8Z9Q0RSTzANOU`CecghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#_@6n

604 memset(prop, 0, sizeof(cydriver.CUmemAllocationProp)) 1:q;13MV45WX7Y8Z9Q0RSTzANOU`CecghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#_@6n

605 prop.type = <cydriver.CUmemAllocationType>alloc_type 1:q;13MV45WX7Y8Z9Q0RSTzANOU`CecghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#_@6n

606 prop.location.type = <cydriver.CUmemLocationType>loc_type 1:q;13MV45WX7Y8Z9Q0RSTzANOU`CecghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#_@6n

607 if self.config.location_type == VirtualMemoryLocationType.HOST_NUMA: 1:q;13MV45WX7Y8Z9Q0RSTzANOU`CecghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#_@6n

608 prop.location.id = self.config.numa_id 1$

609 else: 

610 prop.location.id = self.device.device_id if self.device is not None else -1 1:q;13MV45WX7Y8Z9Q0RSTzANOU`CecghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*(#_@6n

611 prop.allocFlags.gpuDirectRDMACapable = 1 if cfg.gpu_direct_rdma else 0 1:q;13MV45WX7Y8Z9Q0RSTzANOU`CecghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#_@6n

612 prop.requestedHandleTypes = <cydriver.CUmemAllocationHandleType>handle_type 1:q;13MV45WX7Y8Z9Q0RSTzANOU`CecghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#_@6n

613 prop.win32HandleMetaData = NULL 1:q;13MV45WX7Y8Z9Q0RSTzANOU`CecghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#_@6n

614 return 0 1:q;13MV45WX7Y8Z9Q0RSTzANOU`CecghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#_@6n

615  

616 cdef int _fill_access( 

617 self, object cfg, const cydriver.CUmemAllocationProp* prop, 

618 vector[cydriver.CUmemAccessDesc]& descs, 

619 ) except -1: 

620 cdef cydriver.CUmemAccessDesc d 

621 cdef int owner_flags = int(VirtualMemoryResourceOptions._access_to_flags(cfg.self_access)) 1:q;13MV45WX7Y8Z9Q0RSTzANOU`CecghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#_@6n

622 cdef int peer_flags = int(VirtualMemoryResourceOptions._access_to_flags(cfg.peer_access)) 1:q;13MV45WX7Y8Z9Q0RSTzANOU`CecghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#_@6n

623 if owner_flags: 1:q;13MV45WX7Y8Z9Q0RSTzANOU`CecghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#_@6n

624 memset(&d, 0, sizeof(d)) 1:q;13MV45WX7Y8Z9Q0RSTzANOU`CecghDbEHikjda!fBIlFGJK=/)?rs2,-op[]+vw.m%'PLtu^x*$(#_@6n

625 d.location.type = prop.location.type 1:q;13MV45WX7Y8Z9Q0RSTzANOU`CecghDbEHikjda!fBIlFGJK=/)?rs2,-op[]+vw.m%'PLtu^x*$(#_@6n

626 d.location.id = prop.location.id 1:q;13MV45WX7Y8Z9Q0RSTzANOU`CecghDbEHikjda!fBIlFGJK=/)?rs2,-op[]+vw.m%'PLtu^x*$(#_@6n

627 d.flags = <cydriver.CUmemAccess_flags>owner_flags 1:q;13MV45WX7Y8Z9Q0RSTzANOU`CecghDbEHikjda!fBIlFGJK=/)?rs2,-op[]+vw.m%'PLtu^x*$(#_@6n

628 descs.push_back(d) 1:q;13MV45WX7Y8Z9Q0RSTzANOU`CecghDbEHikjda!fBIlFGJK=/)?rs2,-op[]+vw.m%'PLtu^x*$(#_@6n

629 if peer_flags: 1:q;13MV45WX7Y8Z9Q0RSTzANOU`CecghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#_@6n

630 for peer_dev in cfg.peers: 1:q;13MV45WX7Y8Z9Q0RSTzANOU`CecghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#_@6n

631 memset(&d, 0, sizeof(d)) 1)

632 d.location.type = cydriver.CU_MEM_LOCATION_TYPE_DEVICE 1)

633 d.location.id = int(peer_dev) 1)

634 d.flags = <cydriver.CUmemAccess_flags>peer_flags 1)

635 descs.push_back(d) 1)

636 return 0 1:q;13MV45WX7Y8Z9Q0RSTzANOU`CecghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#_@6n

637  

638 cdef size_t _granularity(self, object cfg, const cydriver.CUmemAllocationProp* prop) except? 0: 

639 cdef size_t gran = 0 1:q;13MV45WX7Y8Z9Q0RSTzANOU`CecghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#_@6n

640 cdef int flag = int(VirtualMemoryResourceOptions._granularity_to_driver(cfg.granularity)) 1:q;13MV45WX7Y8Z9Q0RSTzANOU`CecghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#_@6n

641 with nogil: 1:q;13MV45WX7Y8Z9Q0RSTzANOU`CecghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#_@6n

642 HANDLE_RETURN(cydriver.cuMemGetAllocationGranularity( 1:q;13MV45WX7Y8Z9Q0RSTzANOU`CecghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#_@6n

643 &gran, prop, <cydriver.CUmemAllocationGranularity_flags>flag)) 

644 return gran 1:q;13MV45WX7Y8Z9Q0RSTzANOU`CecghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#_@6n

645  

646 cdef int _record_deallocation_stream(self, const DevicePtrHandle& h_ptr, Stream s) except -1: 

647 cdef StreamHandle h 

648 cdef ContextHandle h_ctx 

649 if s is not None and not Stream_is_default_token(s): 1:q;13MV45WX7Y8Z9Q0RSTzANOUCecghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#_@6n

650 h = s._h_stream 1V=[]vw

651 elif self.device is None: 1:q;13M45WX7Y8Z9Q0RSTzANOUCecghDbEHikjda!fBIlFGJK/)?rsy2,-op+.m%'PLtu^x*$(#_@6n

652 # Host-located memory needs no context to free, and a default-stream 

653 # token has no context to bind to: record nothing. 

654 return 0 1^x*$

655 else: 

656 # Bind the legacy default-stream token to the device's primary 

657 # context so the free is ordered correctly no matter what is current 

658 # then, and so allocate() never depends on a current context. 

659 # get_primary_context keeps its own cache; nothing is cached here. 

660 h_ctx = get_primary_context(self.device.device_id) 1:q;13M45WX7Y8Z9Q0RSTzANOUCecghDbEHikjda!fBIlFGJK/)?rsy2,-op+.m%'PLtu(#_@6n

661 if not h_ctx: 1:q;13M45WX7Y8Z9Q0RSTzANOUCecghDbEHikjda!fBIlFGJK/)?rsy2,-op+.m%'PLtu(#_@6n

662 _raise_last_error() 

663 h = create_context_bound_legacy_stream(h_ctx) 1:q;13M45WX7Y8Z9Q0RSTzANOUCecghDbEHikjda!fBIlFGJK/)?rsy2,-op+.m%'PLtu(#_@6n

664 if not h: 1:q;13M45WX7Y8Z9Q0RSTzANOUCecghDbEHikjda!fBIlFGJK/)?rsy2,-op+.m%'PLtu(#_@6n

665 _raise_last_error() 

666 HANDLE_RETURN(set_deallocation_stream(h_ptr, h)) 1:q;13MV45WX7Y8Z9Q0RSTzANOUCecghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu(#_@6n

667 return 0 1:q;13MV45WX7Y8Z9Q0RSTzANOUCecghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu(#_@6n

668  

669 cdef int _copy_deallocation_stream(self, const DevicePtrHandle& dst, const DevicePtrHandle& src) except -1: 

670 cdef StreamHandle h = deallocation_stream(src) 1qcghbijdarsy2opvwmLtuxn

671 if h: 1qcghbijdarsy2opvwmLtuxn

672 HANDLE_RETURN(set_deallocation_stream(dst, h)) 1qcghbijdarsy2opvwmLtun

673 return 0 1qcghbijdarsy2opvwmLtuxn

674  

675 def allocate(self, size_t size, *, stream: Stream | GraphBuilder | None = None) -> VirtualMemoryBuffer: 

676 """ 

677 Allocate a buffer of the given size using CUDA virtual memory. 

678  

679 Parameters 

680 ---------- 

681 size : int 

682 The size in bytes of the buffer to allocate. It is rounded up to the 

683 allocation granularity; the returned buffer reports the rounded size. 

684 stream : :obj:`~_stream.Stream` | :obj:`~graph.GraphBuilder`, optional 

685 Keyword-only. The allocation itself is synchronous. A real stream is 

686 recorded as the buffer's deallocation stream and synchronized when 

687 the buffer closes; with `None` or a default-stream token the legacy 

688 default stream of the resource's device is recorded instead. A 

689 host-located resource records no default stream: its buffers close 

690 without a synchronization unless a real stream was given. 

691  

692 Returns 

693 ------- 

694 VirtualMemoryBuffer 

695 A buffer that owns its reservation, physical allocation and mapping. 

696  

697 Raises 

698 ------ 

699 CUDAError 

700 If any CUDA driver API call fails during allocation. Nothing is 

701 left allocated when this method raises. 

702 OverflowError 

703 If ``size`` rounded up to the granularity does not fit in ``size_t``. 

704 """ 

705 cdef Stream s = None 1:q;13MV45WX7Y8Z9Q0RSTzANOU~`Cec|}ghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#_@6n

706 if stream is not None: 1:q;13MV45WX7Y8Z9Q0RSTzANOU~`Cec|}ghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#_@6n

707 s = Stream_accept(stream) 1:q13MV45WX7Y8Z9Q0RSTzANOUFGJK=2[]vw

708 return self._allocate(self.config, size, s) 1:q;13MV45WX7Y8Z9Q0RSTzANOU~`Cec|}ghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#_@6n

709  

710 cdef Buffer _allocate(self, object cfg, size_t size, Stream s): 

711 """Allocate ``size`` bytes with ``cfg``; ``s`` is the accepted stream or None.""" 

712 cdef cydriver.CUmemAllocationProp prop 

713 cdef vector[cydriver.CUmemAccessDesc] descs 

714 cdef size_t gran, aligned, addr_align 

715 cdef cydriver.CUdeviceptr hint 

716 cdef MemAllocationHandle h_alloc 

717 cdef VaReservationHandle h_res 

718 cdef VaMappingHandle h_map 

719 cdef vector[VaMappingHandle] mappings 

720 cdef VmmRangeHandle rng 

721 cdef DevicePtrHandle h_ptr 

722  

723 if size == 0: 1:q;13MV45WX7Y8Z9Q0RSTzANOU~`Cec|}ghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#_@6n

724 # Nothing to reserve or map: a VMM box over an empty range, so the 

725 # buffer is a VirtualMemoryBuffer like every other. A real stream is 

726 # still recorded so that a later grow inherits it; a default-stream 

727 # token is not, which keeps this path free of driver calls. 

728 h_ptr = deviceptr_create_vmm(0, create_vmm_range(mappings)) 1~|}2

729 if s is not None and not Stream_is_default_token(s): 1~|}2

730 HANDLE_RETURN(set_deallocation_stream(h_ptr, s._h_stream)) 12

731 return Buffer_from_deviceptr_handle(h_ptr, 0, self, None, VirtualMemoryBuffer) 1~|}2

732  

733 self._fill_prop(cfg, &prop) 1:q;13MV45WX7Y8Z9Q0RSTzANOU`CecghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#_@6n

734 self._fill_access(cfg, &prop, descs) 1:q;13MV45WX7Y8Z9Q0RSTzANOU`CecghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#_@6n

735 gran = self._granularity(cfg, &prop) 1:q;13MV45WX7Y8Z9Q0RSTzANOU`CecghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#_@6n

736 aligned = _align_up(size, gran) 1:q;13MV45WX7Y8Z9Q0RSTzANOU`CecghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#_@6n

737 addr_align = cfg.addr_align or gran 1:q;13MV45WX7Y8Z9Q0RSTzANOU`CecghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#_@6n

738 hint = cfg.addr_hint or 0 1:q;13MV45WX7Y8Z9Q0RSTzANOU`CecghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#_@6n

739  

740 # Every handle below is a local: if a later step fails, the locals die 

741 # in reverse order and undo everything created so far. 

742 with nogil: 1:q;13MV45WX7Y8Z9Q0RSTzANOU`CecghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#_@6n

743 h_alloc = create_mem_allocation_handle(aligned, prop, descs.data(), descs.size()) 1:q;13MV45WX7Y8Z9Q0RSTzANOU`CecghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#_@6n

744 if not h_alloc: 1:q;13MV45WX7Y8Z9Q0RSTzANOU`CecghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#_@6n

745 _raise_allocation_error(get_last_error(), prop.requestedHandleTypes) 1`

746 with nogil: 1:q;13MV45WX7Y8Z9Q0RSTzANOUCecghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#_@6n

747 h_res = create_va_reservation_handle(aligned, addr_align, hint) 1:q;13MV45WX7Y8Z9Q0RSTzANOUCecghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#_@6n

748 if not h_res: 1:q;13MV45WX7Y8Z9Q0RSTzANOUCecghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#_@6n

749 _raise_last_error() 1/

750 with nogil: 1:q;13MV45WX7Y8Z9Q0RSTzANOUCecghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#_@6n

751 h_map = create_va_mapping_handle(as_cu(h_res), h_alloc, h_res) 1:q;13MV45WX7Y8Z9Q0RSTzANOUCecghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#_@6n

752 if not h_map: 1:q;13MV45WX7Y8Z9Q0RSTzANOUCecghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#_@6n

753 _raise_last_error() 1)

754  

755 mappings.push_back(h_map) 1:q;13MV45WX7Y8Z9Q0RSTzANOUCecghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#_@6n

756 rng = create_vmm_range(mappings) 1:q;13MV45WX7Y8Z9Q0RSTzANOUCecghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#_@6n

757 h_ptr = deviceptr_create_vmm(as_cu(h_res), rng) 1:q;13MV45WX7Y8Z9Q0RSTzANOUCecghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#_@6n

758 if not h_ptr: 1:q;13MV45WX7Y8Z9Q0RSTzANOUCecghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#_@6n

759 _raise_last_error() 

760 self._record_deallocation_stream(h_ptr, s) 1:q;13MV45WX7Y8Z9Q0RSTzANOUCecghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#_@6n

761 return Buffer_from_deviceptr_handle(h_ptr, aligned, self, None, VirtualMemoryBuffer) 1:q;13MV45WX7Y8Z9Q0RSTzANOUCecghDbEHikjda!fBIlFGJK=/)?rsy2,-op[]+vw.m%'PLtu^x*$(#_@6n

762  

763 def modify_allocation( 

764 self, Buffer buf not None: Buffer, size_t new_size, config: VirtualMemoryResourceOptions | None = None 

765 ) -> VirtualMemoryBuffer: 

766 """ 

767 Grow a buffer of this resource to at least ``new_size`` bytes. 

768  

769 The buffer passed in stays open and usable, and is never returned. The 

770 returned buffer aliases it: both map the same physical memory, which is 

771 freed when the last of the two closes. When the driver can extend the 

772 address range in place, the returned buffer has the same pointer; 

773 otherwise it has a new one and the existing contents are reachable 

774 through both. Closing the returned buffer never closes ``buf``. A 

775 buffer grown from an imported buffer maps imported memory and cannot 

776 be exported again. 

777  

778 Concurrent calls on buffers that alias one another are safe. 

779  

780 Parameters 

781 ---------- 

782 buf : VirtualMemoryBuffer 

783 A buffer returned by :meth:`allocate` or by this method. 

784 new_size : int 

785 The requested total size in bytes; rounded up to the granularity. 

786 config : VirtualMemoryResourceOptions, optional 

787 Configuration for the new physical memory chunk only. Existing 

788 chunks keep the access they were created with, and the resource's 

789 own configuration is unchanged. It must name the resource's 

790 ``location_type``, ``handle_type``, and ``numa_id`` and pass the 

791 same checks as the constructor. 

792 When ``buf`` already covers ``new_size`` there is no new chunk, so 

793 ``config`` has no effect. This method never changes the access of 

794 memory that is already mapped. 

795  

796 Returns 

797 ------- 

798 VirtualMemoryBuffer 

799 A new buffer of at least ``new_size`` and at least ``buf.size`` 

800 bytes. When ``buf`` already covers the request, the result is a 

801 full alias of it and no driver call is made. 

802  

803 Raises 

804 ------ 

805 TypeError 

806 If ``buf`` did not come from this resource. 

807 ValueError 

808 If ``config`` names a different location type, handle type, or 

809 ``numa_id`` than the resource, or the constructor would reject it. 

810 RuntimeError 

811 If ``buf`` is closed, or ``config`` requests GPUDirect RDMA on a 

812 device without support. 

813 OverflowError 

814 If ``new_size`` rounded up to the granularity does not fit in 

815 ``size_t``. 

816 CUDAError 

817 If a driver call fails. ``buf`` is untouched when this method raises. 

818 """ 

819 cdef Buffer b 

820 cdef DevicePtrHandle h_in 

821 cdef size_t in_size 

822 cdef VmmRangeHandle rng, rng_new 

823 cdef object cfg 

824 cdef cydriver.CUmemAllocationProp prop 

825 cdef vector[cydriver.CUmemAccessDesc] descs 

826 cdef vector[VaMappingHandle] mappings 

827 cdef size_t gran, req, total, add, addr_align, offset, i 

828 cdef cydriver.CUdeviceptr base, base_new 

829 cdef MemAllocationHandle h_alloc, a 

830 cdef VaReservationHandle h_res, h_res_new 

831 cdef VaMappingHandle h_map, m2 

832 cdef DevicePtrHandle h_ptr_new 

833 cdef object new_buf 

834  

835 # Every VirtualMemoryBuffer handle comes from deviceptr_create_vmm, so 

836 # the class check is what makes vmm_range() below valid. 

837 if not isinstance(buf, VirtualMemoryBuffer): 2q c g h b i j d a ! r s y 2 o p v w m P L t u x * $ ( Jb# 6 n

838 raise TypeError(f"buf must be a VirtualMemoryBuffer, got {type(buf).__name__}") 2( Jb

839 b = <Buffer>buf 1qcghbijda!rsy2opvwmPLtux*$(#6n

840 Buffer_check_open(b) 1qcghbijda!rsy2opvwmPLtux*$(#6n

841 # Read the input's handle and size once. The handle copy keeps the 

842 # input's box alive for the rest of the call, so a close from another 

843 # thread (unsupported; see concurrency.rst) defers the release instead 

844 # of emptying what this call reads. 

845 h_in = b._h_ptr 1qcghbijda!rsy2opvwmPLtux*$(#6n

846 in_size = b._size 1qcghbijda!rsy2opvwmPLtux*$(#6n

847 if b.memory_resource is not self: 1qcghbijda!rsy2opvwmPLtux*$(#6n

848 raise TypeError("buf was not allocated by this VirtualMemoryResource") 1(

849 cfg = self.config if config is None else check_or_create_options( 1qcghbijda!rsy2opvwmPLtux*$#6n

850 VirtualMemoryResourceOptions, config, "VirtualMemoryResource options", keep_none=False 1!p*$#

851 ) 

852 self._check_config(cfg) 1qcghbijda!rsy2opvwmPLtux*$#6n

853 if in_size == 0: 1qcghbijdarsy2opvwmPLtux6n

854 # An empty buffer maps nothing; the request is a fresh allocation 

855 # that inherits the stream the empty buffer recorded, if any. 

856 new_buf = self._allocate(cfg, new_size, None) 12

857 self._copy_deallocation_stream((<Buffer>new_buf)._h_ptr, h_in) 12

858 return new_buf 12

859 rng = vmm_range(h_in) 1qcghbijdarsyopvwmPLtux6n

860  

861 self._fill_prop(cfg, &prop) 1qcghbijdarsyopvwmPLtux6n

862 self._fill_access(cfg, &prop, descs) 1qcghbijdarsyopvwmPLtux6n

863 gran = self._granularity(cfg, &prop) 1qcghbijdarsyopvwmPLtux6n

864 req = _align_up(new_size, gran) 1qcghbijdarsyopvwmPLtux6n

865 total = vmm_range_total(rng) 1qcghbijdarsyopvwmPLtuxn

866 base = as_cu(h_in) 1qcghbijdarsyopvwmPLtuxn

867  

868 if req <= total: 1qcghbijdarsyopvwmPLtuxn

869 # The range already maps the request: a new buffer over the same 

870 # range, at least as large as the input, with no driver call. The 

871 # result is a distinct object, so closing it never closes ``buf``. 

872 h_ptr_new = deviceptr_create_vmm(base, rng) 1aom

873 if not h_ptr_new: 1aom

874 _raise_last_error() 

875 self._copy_deallocation_stream(h_ptr_new, h_in) 1aom

876 return Buffer_from_deviceptr_handle( 1aom

877 h_ptr_new, req if req > in_size else in_size, self, None, VirtualMemoryBuffer) 1aom

878  

879 # The new chunk is a whole number of granules; the result covers it. 

880 add = _align_up(req - total, gran) 1qcghbijdarsyopvwmPLtuxn

881 req = total + add 1qcghbijdarsyopvwmPLtuxn

882 # The result's range is built from a copy of the input's mappings; the 

883 # input's range is immutable and never changes. 

884 mappings = vmm_range_mappings(rng) 1qcghbijdarsyopvwmPLtuxn

885  

886 # Grow in place: reserve the range right after the current one. The 

887 # driver raises alignment 0 to its default, so the hint is well formed. 

888 with nogil: 1qcghbijdarsyopvwmPLtuxn

889 h_res = create_va_reservation_handle(add, 0, base + total) 1qcghbijdarsyopvwmPLtuxn

890 if not h_res: 1qcghbijdarsyopvwmPLtuxn

891 get_last_error() # the probe may fail; that is not an error here 1P

892 elif as_cu(h_res) != base + total: 1qcghbijdarsyopvwmLtuxn

893 h_res.reset() # granted elsewhere: free it and move instead 1qcghbijdarsyopvwmtuxn

894 else: 

895 with nogil: 1bamLn

896 h_alloc = create_mem_allocation_handle(add, prop, descs.data(), descs.size()) 1bamLn

897 if not h_alloc: 1bamLn

898 _raise_allocation_error(get_last_error(), prop.requestedHandleTypes) 

899 with nogil: 1bamLn

900 h_map = create_va_mapping_handle(base + total, h_alloc, h_res) 1bamLn

901 if not h_map: 1bamLn

902 _raise_last_error() 

903 mappings.push_back(h_map) 1bamLn

904 rng_new = create_vmm_range(mappings) 1bamLn

905 h_ptr_new = deviceptr_create_vmm(base, rng_new) 1bamLn

906 if not h_ptr_new: 1bamLn

907 _raise_last_error() 

908 self._copy_deallocation_stream(h_ptr_new, h_in) 1bamLn

909 return Buffer_from_deviceptr_handle(h_ptr_new, req, self, None, VirtualMemoryBuffer) 1bamLn

910  

911 # Move: a new range that maps every existing allocation, then the new one. 

912 # The allocations are shared with the input buffer's range. 

913 addr_align = cfg.addr_align or gran 1qcghbijdarsyopvwmPtuxn

914 with nogil: 1qcghbijdarsyopvwmPtuxn

915 h_res_new = create_va_reservation_handle(req, addr_align, 0) 1qcghbijdarsyopvwmPtuxn

916 if not h_res_new: 1qcghbijdarsyopvwmPtuxn

917 _raise_last_error() 1P

918 base_new = as_cu(h_res_new) 1qcghbijdarsyopvwmtuxn

919 offset = 0 1qcghbijdarsyopvwmtuxn

920 for i in range(mappings.size()): 1qcghbijdarsyopvwmtuxn

921 a = va_mapping_allocation(mappings[i]) 1qcghbijdarsyopvwmtuxn

922 with nogil: 1qcghbijdarsyopvwmtuxn

923 m2 = create_va_mapping_handle(base_new + offset, a, h_res_new) 1qcghbijdarsyopvwmtuxn

924 if not m2: 1qcghbijdarsyopvwmtuxn

925 _raise_last_error() 

926 offset += mem_allocation_size(a) 1qcghbijdarsyopvwmtuxn

927 mappings[i] = m2 # the input's range still holds the old mapping 1qcghbijdarsyopvwmtuxn

928 with nogil: 1qcghbijdarsyopvwmtuxn

929 h_alloc = create_mem_allocation_handle(add, prop, descs.data(), descs.size()) 1qcghbijdarsyopvwmtuxn

930 if not h_alloc: 1qcghbijdarsyopvwmtuxn

931 _raise_allocation_error(get_last_error(), prop.requestedHandleTypes) 

932 with nogil: 1qcghbijdarsyopvwmtuxn

933 m2 = create_va_mapping_handle(base_new + offset, h_alloc, h_res_new) 1qcghbijdarsyopvwmtuxn

934 if not m2: 1qcghbijdarsyopvwmtuxn

935 _raise_last_error() 

936 mappings.push_back(m2) 1qcghbijdarsyopvwmtuxn

937 rng_new = create_vmm_range(mappings) 1qcghbijdarsyopvwmtuxn

938 h_ptr_new = deviceptr_create_vmm(base_new, rng_new) 1qcghbijdarsyopvwmtuxn

939 if not h_ptr_new: 1qcghbijdarsyopvwmtuxn

940 _raise_last_error() 

941 self._copy_deallocation_stream(h_ptr_new, h_in) 1qcghbijdarsyopvwmtuxn

942 return Buffer_from_deviceptr_handle(h_ptr_new, req, self, None, VirtualMemoryBuffer) 1qcghbijdarsyopvwmtuxn

943  

944 def deallocate(self, ptr: DevicePointerType, size: int, *, stream: Stream | GraphBuilder | None = None) -> None: 

945 """ 

946 Unmap and free one address range that was reserved and mapped outside this resource. 

947  

948 Buffers returned by :meth:`allocate` and :meth:`modify_allocation` free 

949 themselves when they close and never call this method. It exists for 

950 raw pointers wrapped with :meth:`Buffer.from_handle` with ``mr`` set to 

951 this resource: the range must be exactly one reservation, and the caller 

952 must already have released its own ``cuMemCreate`` handle, so the 

953 physical memory is freed by the unmap. 

954  

955 Parameters 

956 ---------- 

957 ptr : DevicePointerType 

958 The start of the reservation. 

959 size : int 

960 The size of the reservation in bytes. 

961 stream : :obj:`~_stream.Stream` | :obj:`~graph.GraphBuilder`, optional 

962 Keyword-only. If given, ``stream.sync()`` is called before the 

963 range is unmapped, except for a default-stream token on a 

964 host-located resource, which has no context to synchronize in. 

965 """ 

966 cdef cydriver.CUdeviceptr devptr = 0 if ptr is None else <cydriver.CUdeviceptr>int(ptr) 2% ' ab

967 cdef size_t nbytes = size 2% ' ab

968 cdef Stream s 

969 if stream is not None: 2% ' ab

970 s = Stream_accept(stream) 2% ' ab

971 # A host-located resource records no stream, so Buffer teardown 

972 # passes an unbound default-stream token, which has no context to 

973 # synchronize in. There is nothing queued on it to wait for. 

974 if self.device is not None or not Stream_is_default_token(s): 2% ' ab

975 s.sync() 2% ' ab

976 if devptr == 0 or nbytes == 0: 2% ' ab

977 return 1%'

978 with nogil: 2ab

979 HANDLE_RETURN(cydriver.cuMemUnmap(devptr, nbytes)) 2ab

980 HANDLE_RETURN(cydriver.cuMemAddressFree(devptr, nbytes)) 2ab

981  

982 @property 

983 def is_device_accessible(self) -> bool: 

984 """ 

985 Indicates whether the allocated memory is accessible from the device. 

986 """ 

987 return self.config.location_type == "device" 2abx

988  

989 @property 

990 def is_host_accessible(self) -> bool: 

991 """ 

992 Indicates whether the allocated memory is accessible from the host. 

993 """ 

994 return self.config.location_type in _HOST_LOCATION_TYPES 2^ x ebfb$

995  

996 @property 

997 def is_ipc_enabled(self) -> bool: 

998 """Whether buffers of this resource can be shared with other processes. 

999  

1000 True when ``config.handle_type`` is ``"posix_fd"`` or ``"fabric"`` on 

1001 Linux and the memory lives on a device; ``handle_type`` is the only switch, there is 

1002 no separate option. With ``handle_type=None`` the allocations cannot 

1003 be exported, and Win32 KMT handles are not transported by cuda.core. 

1004 This is a configuration query and makes no driver call. Host-located 

1005 virtual memory (``location_type`` ``"host"``, ``"host_numa"``, or 

1006 ``"host_numa_current"``) is not shared yet. 

1007 """ 

1008 return ( 

1009 self.config.handle_type in _IPC_HANDLE_TYPES 2hb1 ib3 jbM kblbV mb4 nb5 obW pbX qb7 rbsbY tb8 ubvbZ wb9 xbybQ zb0 AbR BbS CbT Dbz A N EbO FbU Gb~ C e c | } g h D b E H i k j d a f B I l gbHbcbdbLbIbMbF G J K , -

1010 and self.config.location_type not in _HOST_LOCATION_TYPES 2hb1 ib3 jbM kblbV mb4 nb5 obW pbX qb7 rbsbY tb8 ubvbZ wb9 xbybQ zb0 AbR BbS CbT Dbz A N EbO FbU Gb~ C e c | } g h D b E H i k j d a f B I l gbcbdbIbF G J K , -

1011 ) 

1012  

1013 def _import_ipc_buffer(self, _VirtualMemoryDescriptor desc not None, stream) -> VirtualMemoryBuffer: 

1014 """Import a buffer that another process exported; see :meth:`Buffer.from_ipc_descriptor`. 

1015  

1016 Every exported allocation is imported with this resource's handle 

1017 type and checked to live on this resource's device. The allocations 

1018 are then mapped in order into 

1019 one new address reservation with the access descriptors this 

1020 resource's options produce for its device and peers, and the 

1021 deallocation stream is recorded as :meth:`allocate` does. The 

1022 returned buffer owns the imported handles like a buffer from 

1023 :meth:`allocate` owns created ones, reports ``is_mapped``, and cannot 

1024 be exported again. 

1025 """ 

1026 cdef Stream s = None 1~ec|}bkdafIl

1027 cdef object cfg = self.config 1~ec|}bkdafIl

1028 cdef cydriver.CUmemAllocationProp prop 

1029 cdef cydriver.CUmemAllocationProp imported_prop 

1030 cdef vector[cydriver.CUmemAccessDesc] descs 

1031 cdef vector[MemAllocationHandle] allocs 

1032 cdef vector[VaMappingHandle] mappings 

1033 cdef MemAllocationHandle h_alloc 

1034 cdef VaReservationHandle h_res 

1035 cdef VaMappingHandle h_map 

1036 cdef VmmRangeHandle rng 

1037 cdef DevicePtrHandle h_ptr 

1038 cdef Buffer buf 

1039 cdef size_t gran, gran_min = 0, addr_align, chunk, total = 0, offset = 0 1~ec|}bkdafIl

1040 cdef Py_ssize_t n, i 

1041 cdef cydriver.CUdeviceptr hint 

1042 cdef int handle_type 

1043 cdef cydriver.CUmemFabricHandle fh 

1044 cdef void* os_handle 

1045  

1046 if not self.is_ipc_enabled: 1~ec|}bkdafIl

1047 raise RuntimeError("Memory resource is not IPC-enabled") 1I

1048 handle_type = int(VirtualMemoryResourceOptions._handle_type_to_driver(cfg.handle_type)) 1~ec|}bkdafl

1049 if desc.driver_handle_type() != handle_type: 1~ec|}bkdafl

1050 raise ValueError( 1~e

1051 "the descriptor's handle type does not match this resource's " 1~e

1052 f"handle_type={str(cfg.handle_type)!r}; import it with a resource configured like the exporter's" 1~e

1053 ) 

1054 n = len(desc._chunk_sizes) 1ec|}bkdafl

1055 if n != len(desc.handles): 1ec|}bkdafl

1056 raise ValueError("malformed VirtualMemoryResource buffer descriptor") 1e

1057 if stream is not None: 1ec|}bkdafl

1058 s = Stream_accept(stream) 1ec|}bkdafl

1059 if n == 0: 1ec|}bkdafl

1060 if desc._size != 0: 1e|}

1061 raise ValueError( 1e

1062 f"malformed VirtualMemoryResource buffer descriptor: a size of {desc._size} bytes with no " 1e

1063 "exported allocations" 

1064 ) 

1065 # An exported empty buffer: an empty range, as allocate(0) returns. 

1066 h_ptr = deviceptr_create_vmm(0, create_vmm_range(mappings)) 1|}

1067 if s is not None and not Stream_is_default_token(s): 1|}

1068 HANDLE_RETURN(set_deallocation_stream(h_ptr, s._h_stream)) 1|

1069 buf = Buffer_from_deviceptr_handle(h_ptr, 0, self, None, VirtualMemoryBuffer) 1|}

1070 buf._ipc_data = IPCDataForBuffer(None, True) 1|}

1071 return buf 1|}

1072  

1073 self._fill_prop(cfg, &prop) 1ecbkdafl

1074 self._fill_access(cfg, &prop, descs) 1ecbkdafl

1075 gran = self._granularity(cfg, &prop) 1ecbkdafl

1076 # cuMemMap requires the minimum granularity, whatever this resource's 

1077 # granularity option says; the exporter may have used either. 

1078 with nogil: 1ecbkdafl

1079 HANDLE_RETURN(cydriver.cuMemGetAllocationGranularity( 1ecbkdafl

1080 &gran_min, &prop, cydriver.CU_MEM_ALLOC_GRANULARITY_MINIMUM)) 

1081 for chunk_obj in desc._chunk_sizes: 1ecbkdafl

1082 chunk = chunk_obj 1ecbkdafl

1083 if chunk == 0 or chunk % gran_min != 0: 1ecbkdafl

1084 raise ValueError( 1e

1085 f"descriptor chunk size {chunk} is not a positive multiple of the {gran_min}-byte minimum " 1e

1086 "granularity" 

1087 ) 

1088 if chunk > <size_t>-1 - total: 1ecbkdafl

1089 raise OverflowError("the descriptor's chunk sizes do not fit in size_t") 

1090 total += chunk 1ecbkdafl

1091 if desc._size > total: 1ecbkdafl

1092 raise ValueError(f"descriptor size ({desc._size}) exceeds the exported allocations ({total} bytes)") 1e

1093 addr_align = cfg.addr_align or gran 1ecbkdafl

1094 hint = cfg.addr_hint or 0 1ecbkdafl

1095  

1096 # Every handle below is a local: if a later step fails, the locals die 

1097 # in reverse order and release everything imported so far. 

1098 # 

1099 # The driver copies each shared allocation into a handle of its own 

1100 # during cuMemImportFromShareableHandle and keeps no reference to the 

1101 # file descriptor afterwards: the shareable handle and the allocation 

1102 # handle are independent references to the memory, and the CUDA 

1103 # samples and PyTorch close the descriptor right after the import. The 

1104 # buffer therefore does not keep the descriptor; its file descriptors 

1105 # live only as long as the caller holds the descriptor object. 

1106 for i in range(n): 1ecbkdafl

1107 chunk = desc._chunk_sizes[i] 1ecbkdafl

1108 os_handle = desc.handle_ptr(i, &fh) 1ecbkdafl

1109 with nogil: 1ecbkdafl

1110 h_alloc = import_mem_allocation_handle( 1ecbkdafl

1111 os_handle, <cydriver.CUmemAllocationHandleType>handle_type, chunk, descs.data(), descs.size()) 

1112 if not h_alloc: 1ecbkdafl

1113 if handle_type == <int>cydriver.CU_MEM_HANDLE_TYPE_FABRIC: 1e

1114 note = ( 

1115 f"while importing chunk {i + 1} of {n} of a fabric buffer descriptor; the handle may be " 

1116 "stale (the exporting buffer was closed), forged, or exported on a different IMEX channel" 

1117 ) 

1118 else: 

1119 note = ( 

1120 f"while importing chunk {i + 1} of {n} of a VirtualMemoryResource buffer descriptor; either " 1e

1121 "the shared handle does not refer to a CUDA allocation exported with " 

1122 f"handle_type={str(cfg.handle_type)!r}, or the device that owns the memory is not usable in " 1e

1123 "this process (for example, CUDA_VISIBLE_DEVICES hides it)" 

1124 ) 

1125 _raise_last_error_noting(note) 1e

1126 # The exporter chose where the memory lives. This resource must map 

1127 # memory of that kind on that device, or its access descriptors 

1128 # would describe the wrong location. 

1129 with nogil: 1ecbkdafl

1130 HANDLE_RETURN(cydriver.cuMemGetAllocationPropertiesFromHandle(&imported_prop, as_cu(h_alloc))) 1ecbkdafl

1131 if imported_prop.location.type != prop.location.type or ( 1ecbkdafl

1132 prop.location.type == cydriver.CU_MEM_LOCATION_TYPE_DEVICE 1ecbkdafl

1133 and imported_prop.location.id != prop.location.id 1ecbkdafl

1134 ): 

1135 owner_detail = "" 

1136 owner_uuid = getattr(desc, "owner_uuid", None) 

1137 if owner_uuid is not None: 

1138 try: 

1139 owner = _device_from_uuid(owner_uuid) 

1140 except RuntimeError: 

1141 owner_detail = ( 

1142 f"memory belongs to the device with UUID {owner_uuid}, " 

1143 "which is not visible in this process; " 

1144 ) 

1145 else: 

1146 owner_detail = ( 

1147 f"memory belongs to the device with UUID {owner_uuid}, " 

1148 f"which is device {owner.device_id} in this process; " 

1149 ) 

1150 raise ValueError( 

1151 f"{owner_detail}chunk {i + 1} of the descriptor is memory on {_describe_location(imported_prop.location)}, " 

1152 f"but this resource maps memory on {_describe_location(prop.location)}; import the descriptor " 

1153 "with a VirtualMemoryResource for the device that owns the memory, and name other devices " 

1154 "in its peers option" 

1155 ) 

1156 allocs.push_back(h_alloc) 1ecbkdafl

1157 with nogil: 1ecbkdafl

1158 h_res = create_va_reservation_handle(total, addr_align, hint) 1ecbkdafl

1159 if not h_res: 1ecbkdafl

1160 _raise_last_error() 

1161 for i in range(n): 1ecbkdafl

1162 chunk = mem_allocation_size(allocs[<size_t>i]) 1ecbkdafl

1163 with nogil: 1ecbkdafl

1164 h_map = create_va_mapping_handle(as_cu(h_res) + offset, allocs[<size_t>i], h_res) 1ecbkdafl

1165 if not h_map: 1ecbkdafl

1166 _raise_last_error_noting( 1c

1167 f"while mapping chunk {i + 1} of {n} ({chunk} bytes) of a VirtualMemoryResource buffer " 1c

1168 "descriptor; a chunk size that does not match the exported allocation fails here, and the " 

1169 "sizes come from the exporting peer" 

1170 ) 

1171 mappings.push_back(h_map) 1ecbkdafl

1172 offset += chunk 1ecbkdafl

1173 rng = create_vmm_range(mappings) 1ecbkdafl

1174 h_ptr = deviceptr_create_vmm(as_cu(h_res), rng) 1ecbkdafl

1175 if not h_ptr: 1ecbkdafl

1176 _raise_last_error() 

1177 self._record_deallocation_stream(h_ptr, s) 1ecbkdafl

1178 buf = Buffer_from_deviceptr_handle(h_ptr, desc._size, self, None, VirtualMemoryBuffer) 1ecbkdafl

1179 buf._ipc_data = IPCDataForBuffer(None, True) 1ecbkdafl

1180 return buf 1ecbkdafl

1181  

1182 @property 

1183 def device_id(self) -> int: 

1184 """ 

1185 Get the device ID associated with this memory resource. 

1186  

1187 Returns: 

1188 int: CUDA device ID. -1 if the memory resource allocates host memory 

1189 """ 

1190 return self.device.device_id if self.device is not None else -1 2bb, - p x ebfb

1191  

1192 def __repr__(self) -> str: 

1193 """ 

1194 Return a string representation of the VirtualMemoryResource. 

1195  

1196 Returns: 

1197 str: A string describing the object 

1198 """ 

1199 return f"<VirtualMemoryResource device={self.device}>" 2NbKb

1200  

1201  

1202def _reconstruct_virtual_memory_resource( 

1203 cls: type, owner_uuid: str | None, peer_uuids: tuple[str, ...], config: VirtualMemoryResourceOptions 

1204) -> VirtualMemoryResource: 

1205 """Rebuild a pickled resource with the receiving process's device ordinals.""" 

1206 device = _device_from_uuid(owner_uuid) if owner_uuid is not None else 0 2bb

1207 peers = tuple(_device_from_uuid(peer_uuid).device_id for peer_uuid in peer_uuids) 2bb

1208 return cls(device, replace(config, peers=peers)) 2bb

1209  

1210  

1211cdef _VirtualMemoryDescriptor _export_ipc_descriptor(Buffer buf): 

1212 """Export the allocations that back ``buf`` as shareable handles, in address order. 

1213  

1214 Only the allocations that cover ``buf.size`` are exported; a buffer's size 

1215 is a prefix of its range. Each file descriptor is owned by an 

1216 :class:`IPCAllocationHandle` in the new descriptor and closed with it; 

1217 nothing is cached on the buffer. A buffer that contains memory imported 

1218 from another process is refused before any driver call: the driver 

1219 exports only allocations this process created with the handle type, and 

1220 every allocation carries its provenance (``mem_allocation_is_imported``) 

1221 into every range that maps it. 

1222 """ 

1223 cdef VirtualMemoryResource mr = <VirtualMemoryResource>buf._memory_resource 113MV45WX7Y8Z9Q0RSTzANOU~Cec|}ghDbEHikjdafBIlFGJK

1224 cdef vector[VaMappingHandle] mappings 

1225 cdef vector[MemAllocationHandle] allocs 

1226 cdef MemAllocationHandle h_alloc 

1227 cdef cydriver.CUresult status 

1228 cdef size_t i, n, chunk, offset = 0 113MV45WX7Y8Z9Q0RSTzANOU~Cec|}ghDbEHikjdafBIlFGJK

1229 cdef int handle_type 

1230 cdef int fd = -1 113MV45WX7Y8Z9Q0RSTzANOU~Cec|}ghDbEHikjdafBIlFGJK

1231 cdef cydriver.CUmemFabricHandle fh 

1232 cdef list sizes = [] 113MV45WX7Y8Z9Q0RSTzANOU~Cec|}ghDbEHikjdafBIlFGJK

1233 cdef list handles = [] 113MV45WX7Y8Z9Q0RSTzANOU~Cec|}ghDbEHikjdafBIlFGJK

1234  

1235 if not mr.is_ipc_enabled: 113MV45WX7Y8Z9Q0RSTzANOU~Cec|}ghDbEHikjdafBIlFGJK

1236 raise RuntimeError("Memory resource is not IPC-enabled") 1I

1237 handle_type = int(VirtualMemoryResourceOptions._handle_type_to_driver(mr.config.handle_type)) 113MV45WX7Y8Z9Q0RSTzANOU~Cec|}ghDbEHikjdafBIlFGJK

1238 mappings = vmm_range_mappings(vmm_range(buf._h_ptr)) 113MV45WX7Y8Z9Q0RSTzANOU~Cec|}ghDbEHikjdafBIlFGJK

1239 for i in range(mappings.size()): 113MV45WX7Y8Z9Q0RSTzANOU~Cec|}ghDbEHikjdafBIlFGJK

1240 if offset >= buf._size: 113MV45WX7Y8Z9Q0RSTzANOUCecghDbEHikjdafBIlFGJK

1241 break 

1242 h_alloc = va_mapping_allocation(mappings[i]) 113MV45WX7Y8Z9Q0RSTzANOUCecghDbEHikjdafBIlFGJK

1243 allocs.push_back(h_alloc) 113MV45WX7Y8Z9Q0RSTzANOUCecghDbEHikjdafBIlFGJK

1244 offset += mem_allocation_size(h_alloc) 113MV45WX7Y8Z9Q0RSTzANOUCecghDbEHikjdafBIlFGJK

1245 n = allocs.size() 113MV45WX7Y8Z9Q0RSTzANOU~Cec|}ghDbEHikjdafBIlFGJK

1246 for i in range(n): 113MV45WX7Y8Z9Q0RSTzANOU~Cec|}ghDbEHikjdafBIlFGJK

1247 if mem_allocation_is_imported(allocs[i]): 113MV45WX7Y8Z9Q0RSTzANOUCecghDbEHikjdafBIlFGJK

1248 raise RuntimeError( 1af

1249 f"this buffer contains memory imported from another process (allocation {i + 1} of {n}); imported " 1af

1250 "memory cannot be exported again. Forward the descriptor it was imported from, or copy the data " 

1251 "into a buffer this process allocated." 

1252 ) 

1253 for i in range(n): 113MV45WX7Y8Z9Q0RSTzANOU~Cec|}ghDbEHikjdafBIlFGJK

1254 h_alloc = allocs[i] 113MV45WX7Y8Z9Q0RSTzANOUCecghDbEHikjdafBIlFGJK

1255 chunk = mem_allocation_size(h_alloc) 113MV45WX7Y8Z9Q0RSTzANOUCecghDbEHikjdafBIlFGJK

1256 if handle_type == <int>cydriver.CU_MEM_HANDLE_TYPE_FABRIC: 113MV45WX7Y8Z9Q0RSTzANOUCecghDbEHikjdafBIlFGJK

1257 # The driver fills its fields of the 64 bytes and leaves the padding; zero it first so that two 

1258 # exports of one allocation carry the same bytes and no stack bytes travel in a descriptor. 

1259 memset(&fh, 0, sizeof(fh)) 

1260 with nogil: 

1261 HANDLE_RETURN(cydriver.cuMemExportToShareableHandle( 

1262 <void*>&fh, as_cu(h_alloc), <cydriver.CUmemAllocationHandleType>handle_type, 0)) 

1263 handles.append(cpython.PyBytes_FromStringAndSize(<char*>fh.data, sizeof(fh.data))) 

1264 sizes.append(chunk) 

1265 continue 

1266 with nogil: 113MV45WX7Y8Z9Q0RSTzANOUCecghDbEHikjdafBIlFGJK

1267 status = cydriver.cuMemExportToShareableHandle( 113MV45WX7Y8Z9Q0RSTzANOUCecghDbEHikjdafBIlFGJK

1268 <void*>&fd, as_cu(h_alloc), <cydriver.CUmemAllocationHandleType>handle_type, 0) 

1269 _check_noting( 113MV45WX7Y8Z9Q0RSTzANOUCecghDbEHikjdafBIlFGJK

1270 status, 

1271 f"while exporting allocation {i + 1} of {n} of a VirtualMemoryResource buffer; each exported " 113MV45WX7Y8Z9Q0RSTzANOUCecghDbEHikjdafBIlFGJK

1272 "allocation takes one file descriptor, so a process near its file descriptor limit fails here", 

1273 ) 

1274 try: 113MV45WX7Y8Z9Q0RSTzANOUCecghDbEHikjdafBIlFGJK

1275 handle = IPCAllocationHandle._init(fd, None) 113MV45WX7Y8Z9Q0RSTzANOUCecghDbEHikjdafBIlFGJK

1276 except: # noqa: E722 rollback-then-raise: the fd is not owned yet 

1277 # nvbug 6977893: an Orin driver can return a negative fd despite success. 

1278 if fd >= 0: 

1279 os.close(fd) 

1280 raise 

1281 # The handle owns the fd now; if append fails, the handle closes it once. 

1282 handles.append(handle) 113MV45WX7Y8Z9Q0RSTzANOUCecghDbEHikjdafBIlFGJK

1283 sizes.append(chunk) 113MV45WX7Y8Z9Q0RSTzANOUCecghDbEHikjdafBIlFGJK

1284 if handle_type == <int>cydriver.CU_MEM_HANDLE_TYPE_FABRIC: 113MV45WX7Y8Z9Q0RSTzANOU~Cec|}ghDbEHikjdafBIlFGJK

1285 return VirtualMemoryFabricBufferDescriptor._from_exports( 1~

1286 tuple(sizes), tuple(handles), buf._size, mr.device.uuid) 1~

1287 return VirtualMemoryFdBufferDescriptor._from_exports(tuple(sizes), tuple(handles), buf._size) 113MV45WX7Y8Z9Q0RSTzANOU~Cec|}ghDbEHikjdafBIlFGJK