Coverage for cuda/core/_device_resources.pyx: 80.55%

293 statements  

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

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

2# 

3# SPDX-License-Identifier: Apache-2.0 

4  

5from __future__ import annotations 

6  

7from collections.abc import Sequence as SequenceABC 

8from dataclasses import dataclass 

9from typing import TYPE_CHECKING 

10  

11if TYPE_CHECKING: 

12 from cuda.core._device import Device 

13 from cuda.core.typing import WorkqueueSharingScopeType 

14  

15from libc.stdint cimport intptr_t 

16from libc.stdlib cimport free, malloc 

17from libc.string cimport memset 

18  

19from cuda.bindings cimport cydriver 

20from cuda.core._rt cimport ContextHandle, GreenCtxHandle, as_cu, get_context_green_ctx 

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

22from cuda.core._utils.cuda_utils import is_sequence 

23from cuda.core._utils.version cimport cy_driver_version 

24from cuda.core._utils.validators import check_str_enum 

25  

26  

27__all__ = [ 

28 "DeviceResources", 

29 "SMResource", 

30 "SMResourceOptions", 

31 "WorkqueueResource", 

32 "WorkqueueResourceOptions", 

33] 

34  

35  

36# Module-level cached version checks (trinary: 0=unchecked, 1=supported, -1=unsupported) 

37cdef int _green_ctx_checked = 0 

38cdef int _workqueue_checked = 0 

39cdef str _green_ctx_err_msg = "" 

40cdef str _workqueue_err_msg = "" 

41  

42  

43cdef inline int _check_green_ctx_support() except?-1: 

44 global _green_ctx_checked, _green_ctx_err_msg 

45 if _green_ctx_checked == 1: 1caIGdFJE8CefsKpDghijklmnLMNOPvQuRqSwTrUtVWXzYZB012697!+#5$H%)'(x3oy4b

46 return 0 1caIGdFJE8CefsKpDghijklmnLMNOPvQuRqSwTrUtVWXzYZB012697!+#5$H%)'(x3oy4b

47 if _green_ctx_checked == -1: 1b

48 raise RuntimeError(_green_ctx_err_msg) 

49 cdef tuple drv = cy_driver_version() 1b

50 if drv < (12, 4, 0): 1b

51 _green_ctx_err_msg = ( 

52 "Green context support requires CUDA driver 12.4 or newer " 

53 f"(current driver: {'.'.join(map(str, drv))})" 

54 ) 

55 _green_ctx_checked = -1 

56 raise RuntimeError(_green_ctx_err_msg) 

57 _green_ctx_checked = 1 1b

58 return 0 1b

59  

60  

61cdef inline int _check_workqueue_support() except?-1: 

62 global _workqueue_checked, _workqueue_err_msg 

63 if _workqueue_checked == 1: 1E8CpD697!+#5$H%)'(

64 return 0 1E8Cp697!+#5$H%)'(

65 if _workqueue_checked == -1: 1D

66 raise RuntimeError(_workqueue_err_msg) 

67 cdef tuple drv = cy_driver_version() 1D

68 if drv < (13, 1, 0): 1D

69 _workqueue_err_msg = ( 

70 "WorkqueueResource requires CUDA driver 13.1 or newer " 

71 f"(current driver: {'.'.join(map(str, drv))})" 

72 ) 

73 _workqueue_checked = -1 

74 raise RuntimeError(_workqueue_err_msg) 

75 _workqueue_checked = 1 1AD

76 return 0 1D

77  

78  

79@dataclass 

80cdef class SMResourceOptions: 

81 """Customizable :obj:`SMResource.split` options. 

82  

83 Each field accepts a scalar (for a single group) or a ``Sequence`` 

84 (for multiple groups). ``count`` drives the number of groups; other 

85 ``Sequence`` fields must match its length. 

86  

87 Attributes 

88 ---------- 

89 count : int or Sequence[int], optional 

90 Requested SM count per group. ``None`` means discovery mode 

91 (auto-detect). (Default to ``None``) 

92 coscheduled_sm_count : int or Sequence[int], optional 

93 Minimum number of SMs guaranteed to be co-scheduled in each 

94 group. (Default to ``None``) 

95 preferred_coscheduled_sm_count : int or Sequence[int], optional 

96 Preferred co-scheduled SM count; the driver tries to satisfy 

97 this but may fall back to ``coscheduled_sm_count``. 

98 (Default to ``None``) 

99 backfill : bool or Sequence[bool], optional 

100 If ``True``, allow the driver to relax the co-scheduling 

101 constraint when assigning SMs. This enables requesting 

102 arbitrary aligned SM counts that the driver would otherwise 

103 reject due to hardware topology constraints. 

104 (Default to ``False``) 

105 """ 

106  

107 count: int | SequenceABC[int] | None = None 

108 coscheduled_sm_count: int | SequenceABC[int] | None = None 

109 preferred_coscheduled_sm_count: int | SequenceABC[int] | None = None 

110 backfill: bool | SequenceABC[bool] = False 

111  

112  

113@dataclass(init=False) 

114cdef class WorkqueueResourceOptions: 

115 """Customizable :obj:`WorkqueueResource.configure` options. 

116  

117 Attributes 

118 ---------- 

119 sharing_scope : :class:`~cuda.core.typing.WorkqueueSharingScopeType` | str, optional 

120 Workqueue sharing scope. Accepted values: ``"device_ctx"`` or 

121 ``"green_ctx_balanced"``. 

122 concurrency_limit : int, optional 

123 Expected maximum number of concurrent stream-ordered 

124 workloads. Must be ``>= 1`` when set. The effective 

125 driver-side cap is ``CUDA_DEVICE_MAX_CONNECTIONS`` 

126 (typically ``[1, 32]``); configurations may exceed 

127 this cap, but the driver will not guarantee that work 

128 submission remains non-overlapping. (Default to ``None``) 

129 """ 

130  

131 sharing_scope: WorkqueueSharingScopeType | str | None = None 

132 concurrency_limit: int | None = None 

133  

134 def __init__( 

135 self, 

136 sharing_scope: WorkqueueSharingScopeType | str | None = None, 

137 concurrency_limit: int | None = None, 

138 ): 

139 from cuda.core.typing import WorkqueueSharingScopeType 1p;=67+5H)[

140 check_str_enum(sharing_scope, WorkqueueSharingScopeType, allow_none=True) 1p;=67+5H)[

141 if concurrency_limit is not None and concurrency_limit < 1: 1p;=67+5H)

142 raise ValueError( 1;=

143 f"concurrency_limit must be >= 1, got {concurrency_limit}" 1;=

144 ) 

145 self.sharing_scope = sharing_scope 1p67+5H)

146 self.concurrency_limit = concurrency_limit 1p67+5H)

147  

148  

149cdef inline int _validate_split_field_length( 

150 object value, str field_name, int n_groups, bint count_is_scalar 

151) except?-1: 

152 if count_is_scalar: 1cadefspghijklmnvuqwrtzB,*xoyb

153 if is_sequence(value): 1cdefpghijklmnvuqwzB,xoyb

154 raise ValueError( 1,

155 f"{field_name} is a Sequence but count is scalar; " 1,

156 "count must be a Sequence to specify multiple groups" 

157 ) 

158 elif is_sequence(value) and len(value) != n_groups: 1asrt*

159 raise ValueError( 1*

160 f"{field_name} has length {len(value)}, expected {n_groups} " 1*

161 "(must match count)" 

162 ) 

163 return 0 1cadefspghijklmnvuqwrtzBxoyb

164  

165  

166cdef inline int _resolve_group_count(SMResourceOptions options) except?-1: 

167 cdef object count = options.count 1cadefspghijklmnvuqwrt/:z-B,*xoyb

168 cdef int n_groups 

169 cdef bint count_is_scalar 

170  

171 if count is None or isinstance(count, int): 1cadefspghijklmnvuqwrt/:z-B,*xoyb

172 n_groups = 1 1cdefpghijklmnvuqwzB,xoyb

173 count_is_scalar = True 1cdefpghijklmnvuqwzB,xoyb

174 elif is_sequence(count): 1asrt/:-*

175 n_groups = <int>len(count) 1asrt-*

176 if n_groups == 0: 1asrt-*

177 raise ValueError("count sequence must not be empty") 1-

178 count_is_scalar = False 1asrt*

179 else: 

180 raise TypeError(f"count must be int, Sequence, or None, got {type(count)}") 1/:

181  

182 _validate_split_field_length( 1cadefspghijklmnvuqwrtzB,*xoyb

183 options.coscheduled_sm_count, 1cadefspghijklmnvuqwrtzB,*xoyb

184 "coscheduled_sm_count", 

185 n_groups, 

186 count_is_scalar, 

187 ) 

188 _validate_split_field_length( 1cadefspghijklmnvuqwrtzBxoyb

189 options.preferred_coscheduled_sm_count, 1cadefspghijklmnvuqwrtzBxoyb

190 "preferred_coscheduled_sm_count", 

191 n_groups, 

192 count_is_scalar, 

193 ) 

194 _validate_split_field_length( 1cadefspghijklmnvuqwrtzBxoyb

195 options.backfill, 1cadefspghijklmnvuqwrtzBxoyb

196 "backfill", 

197 n_groups, 

198 count_is_scalar, 

199 ) 

200 return n_groups 1cadefspghijklmnvuqwrtzBxoyb

201  

202  

203cdef inline object _broadcast_field(object value, int n_groups): 

204 if is_sequence(value): 1cadefspghijklmnvuqwrtzBxoyb

205 return list(value) 1asrt

206 return [value] * n_groups 1cadefspghijklmnvuqwrtzBxoyb

207  

208  

209cdef inline unsigned int _to_sm_count(object value) except? 0: 

210 """Convert a count value to unsigned int. None maps to 0 (discovery).""" 

211 if value is None: 1cadefspghijklmnvuqwrtzBxoyb

212 return 0 1cdefpghijklmnvuqzxoyb

213 if value < 0: 1aswrtB

214 raise ValueError(f"count must be non-negative, got {value}") 1B

215 return <unsigned int>(value) 1aswrt

216  

217  

218cdef int _structured_split_checked = 0 

219  

220cdef inline bint _can_use_structured_sm_split(): 

221 """Whether the driver provides cuDevSmResourceSplit, a 13.1 driver API. Cached. 

222  

223 Every cuda-bindings at or above the CUDA 13 floor exports it. Only the driver can lack it.""" 

224 global _structured_split_checked 

225 if _structured_split_checked != 0: 1cadefspghijklmnvuqwrtzBxoyb

226 return _structured_split_checked == 1 1cadefspghijklmnvuqwrtzBxoy

227 IF CUDA_CORE_BUILD_MAJOR >= 13: 

228 if cy_driver_version() >= (13, 1, 0): 1b

229 _structured_split_checked = 1 1b

230 return True 1b

231 _structured_split_checked = -1 

232 return False 

233  

234  

235cdef object _resolve_split_by_count_request(SMResourceOptions options): 

236 cdef int n_groups = _resolve_group_count(options) 

237 cdef list counts = _broadcast_field(options.count, n_groups) 

238 cdef object first = counts[0] 

239 cdef object value 

240  

241 if options.coscheduled_sm_count is not None: 

242 raise RuntimeError( 

243 "SMResourceOptions.coscheduled_sm_count requires the CUDA 13.1 " 

244 "structured SM split API" 

245 ) 

246 if options.preferred_coscheduled_sm_count is not None: 

247 raise RuntimeError( 

248 "SMResourceOptions.preferred_coscheduled_sm_count requires the " 

249 "CUDA 13.1 structured SM split API" 

250 ) 

251  

252 for value in counts[1:]: 

253 if value != first: 

254 raise RuntimeError( 

255 "CUDA 12 SM splitting only supports homogeneous count values; " 

256 "use CUDA 13.1 or newer for per-group counts" 

257 ) 

258  

259 cdef unsigned int min_count = _to_sm_count(first) 

260 return n_groups, min_count 

261  

262  

263IF CUDA_CORE_BUILD_MAJOR >= 13: 

264 cdef inline int _fill_group_params( 

265 cydriver.CU_DEV_SM_RESOURCE_GROUP_PARAMS* params, 

266 int n_groups, 

267 SMResourceOptions options, 

268 ) except?-1: 

269 cdef list counts = _broadcast_field(options.count, n_groups) 1cadefspghijklmnvuqwrtzBxoyb

270 cdef list coscheduled = _broadcast_field(options.coscheduled_sm_count, n_groups) 1cadefspghijklmnvuqwrtzBxoyb

271 cdef list preferred = _broadcast_field(options.preferred_coscheduled_sm_count, n_groups) 1cadefspghijklmnvuqwrtzBxoyb

272 cdef list backfills = _broadcast_field(options.backfill, n_groups) 1cadefspghijklmnvuqwrtzBxoyb

273 cdef int i 

274  

275 for i in range(n_groups): 1cadefspghijklmnvuqwrtzBxoyb

276 memset(&params[i], 0, sizeof(cydriver.CU_DEV_SM_RESOURCE_GROUP_PARAMS)) 1cadefspghijklmnvuqwrtzBxoyb

277 params[i].smCount = _to_sm_count(counts[i]) 1cadefspghijklmnvuqwrtzBxoyb

278 if coscheduled[i] is not None: 1cadefspghijklmnvuqwrtzxoyb

279 params[i].coscheduledSmCount = <unsigned int>(coscheduled[i]) 1u

280 if preferred[i] is not None: 1cadefspghijklmnvuqwrtzxoyb

281 params[i].preferredCoscheduledSmCount = <unsigned int>(preferred[i]) 

282 params[i].flags = ( 1cadefspghijklmnvuqwrtzxoyb

283 cydriver.CUdevSmResourceGroup_flags.CU_DEV_SM_RESOURCE_GROUP_BACKFILL 

284 if backfills[i] else 0 1cadefspghijklmnvuqwrtzxoyb

285 ) 

286 return 0 1cadefspghijklmnvuqwrtzxoyb

287  

288  

289 cdef object _split_with_general_api(SMResource sm, SMResourceOptions options, bint dry_run): 

290 cdef int n_groups = _resolve_group_count(options) 1cadefspghijklmnvuqwrtzBxoyb

291 cdef cydriver.CUdevResource* result = NULL 1cadefspghijklmnvuqwrtzBxoyb

292 cdef cydriver.CUdevResource remaining 

293 cdef cydriver.CUdevResource synth 

294 cdef cydriver.CU_DEV_SM_RESOURCE_GROUP_PARAMS* params = NULL 1cadefspghijklmnvuqwrtzBxoyb

295 cdef list groups = [] 1cadefspghijklmnvuqwrtzBxoyb

296 cdef int i 

297  

298 params = <cydriver.CU_DEV_SM_RESOURCE_GROUP_PARAMS*>malloc( 1cadefspghijklmnvuqwrtzBxoyb

299 n_groups * sizeof(cydriver.CU_DEV_SM_RESOURCE_GROUP_PARAMS) 

300 ) 

301 if params == NULL: 1cadefspghijklmnvuqwrtzBxoyb

302 raise MemoryError() 

303  

304 try: 1cadefspghijklmnvuqwrtzBxoyb

305 _fill_group_params(params, n_groups, options) 1cadefspghijklmnvuqwrtzBxoyb

306  

307 if not dry_run: 1cadefspghijklmnvuqwrtzxoyb

308 result = <cydriver.CUdevResource*>malloc( 1cadefspghijklmnvuqwrtxoyb

309 n_groups * sizeof(cydriver.CUdevResource) 

310 ) 

311 if result == NULL: 1cadefspghijklmnvuqwrtxoyb

312 raise MemoryError() 

313  

314 memset(&remaining, 0, sizeof(cydriver.CUdevResource)) 1cadefspghijklmnvuqwrtzxoyb

315 with nogil: 1cadefspghijklmnvuqwrtzxoyb

316 HANDLE_RETURN(cydriver.cuDevSmResourceSplit( 1cadefspghijklmnvuqwrtzxoyb

317 result, 

318 <unsigned int>(n_groups), 

319 &sm._resource, 

320 &remaining, 

321 0, 

322 params, 

323 )) 

324  

325 if result != NULL: 1cadefspghijklmnvuqwrtzxoyb

326 for i in range(n_groups): 1cadefspghijklmnvuqwrtxoyb

327 groups.append(SMResource._from_split_resource(result[i], sm, True)) 1cadefspghijklmnvuqwrtxoyb

328 return groups, SMResource._from_split_resource(remaining, sm, True) 1cadefspghijklmnvuqwrtxoyb

329  

330 for i in range(n_groups): 1qz

331 memset(&synth, 0, sizeof(cydriver.CUdevResource)) 1qz

332 synth.type = cydriver.CUdevResourceType.CU_DEV_RESOURCE_TYPE_SM 1qz

333 synth.sm.smCount = params[i].smCount 1qz

334 groups.append(SMResource._from_split_resource(synth, sm, False)) 1qz

335 return groups, SMResource._from_split_resource(remaining, sm, False) 1qz

336 finally: 

337 if params != NULL: 1cadefspghijklmnvuqwrtzxoyb

338 free(params) 1cadefspghijklmnvuqwrtzBxoyb

339 if result != NULL: 1cadefspghijklmnvuqwrtzBxoyb

340 free(result) 1cadefspghijklmnvuqwrtxoyb

341ELSE: 

342 cdef object _split_with_general_api(SMResource sm, SMResourceOptions options, bint dry_run): 

343 raise RuntimeError( 

344 "SMResource.split() requires cuda.core to be built with CUDA 13.x bindings" 

345 ) 

346  

347  

348cdef object _split_with_count_api(SMResource sm, SMResourceOptions options, bint dry_run): 

349 cdef object request = _resolve_split_by_count_request(options) 

350 cdef unsigned int nb_groups = <unsigned int>(request[0]) 

351 cdef unsigned int min_count = <unsigned int>(request[1]) 

352 cdef unsigned int actual_groups = nb_groups 

353 cdef cydriver.CUdevResource* result = NULL 

354 cdef cydriver.CUdevResource remaining 

355 cdef list groups = [] 

356 cdef unsigned int i 

357  

358 result = <cydriver.CUdevResource*>malloc(nb_groups * sizeof(cydriver.CUdevResource)) 

359 if result == NULL: 

360 raise MemoryError() 

361  

362 try: 

363 memset(&remaining, 0, sizeof(cydriver.CUdevResource)) 

364 with nogil: 

365 HANDLE_RETURN(cydriver.cuDevSmResourceSplitByCount( 

366 result, 

367 &actual_groups, 

368 &sm._resource, 

369 &remaining, 

370 0, 

371 min_count, 

372 )) 

373  

374 for i in range(actual_groups): 

375 if dry_run: 

376 groups.append(SMResource._from_split_resource(result[i], sm, False)) 

377 else: 

378 groups.append(SMResource._from_split_resource(result[i], sm, True)) 

379 if dry_run: 

380 return groups, SMResource._from_split_resource(remaining, sm, False) 

381 return groups, SMResource._from_split_resource(remaining, sm, True) 

382 finally: 

383 free(result) 

384  

385  

386cdef inline unsigned int _sm_resource_granularity(int device_id) except? 0: 

387 cdef int major 

388  

389 with nogil: 

390 HANDLE_RETURN(cydriver.cuDeviceGetAttribute( 

391 &major, 

392 cydriver.CUdevice_attribute.CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR, 

393 <cydriver.CUdevice>(device_id), 

394 )) 

395 if major >= 9: 

396 return 8 

397 return 2 

398  

399  

400cdef inline unsigned int _fallback_if_zero(unsigned int value, unsigned int fallback) noexcept: 

401 if value != 0: 1cadefspghijklmnvuqwrtzxoyb

402 return value 1cadefspghijklmnvuqwrtxoyb

403 return fallback 1cdefpghijklmnvuqrzxoyb

404  

405  

406cdef class SMResource: 

407 """Represent an SM (streaming multiprocessor) resource partition. 

408  

409 Instances are returned by :obj:`DeviceResources.sm` or 

410 :meth:`SMResource.split` and cannot be instantiated directly. 

411 """ 

412  

413 def __init__(self, *args, **kwargs): 

414 raise RuntimeError( 1@

415 "SMResource cannot be instantiated directly. " 

416 "Use dev.resources.sm or SMResource.split()." 

417 ) 

418  

419 @staticmethod 

420 cdef SMResource _from_dev_resource(cydriver.CUdevResource res, int device_id): 

421 cdef SMResource self = SMResource.__new__(SMResource) 1caIGdFJCefKDghijklmnLMNOPQRSTUVWXYZ0123o4b

422 self._resource = res 1caIGdFJCefKDghijklmnLMNOPQRSTUVWXYZ0123o4b

423 self._sm_count = res.sm.smCount 1caIGdFJCefKDghijklmnLMNOPQRSTUVWXYZ0123o4b

424 IF CUDA_CORE_BUILD_MAJOR >= 13: 

425 self._min_partition_size = res.sm.minSmPartitionSize 1caIGdFJCefKDghijklmnLMNOPQRSTUVWXYZ0123o4b

426 self._coscheduled_alignment = res.sm.smCoscheduledAlignment 1caIGdFJCefKDghijklmnLMNOPQRSTUVWXYZ0123o4b

427 self._flags = res.sm.flags 1caIGdFJCefKDghijklmnLMNOPQRSTUVWXYZ0123o4b

428 ELSE: 

429 self._min_partition_size = _sm_resource_granularity(device_id) 

430 self._coscheduled_alignment = self._min_partition_size 

431 self._flags = 0 

432 self._is_usable = True 1caIGdFJCefKDghijklmnLMNOPQRSTUVWXYZ0123o4b

433 return self 1caIGdFJCefKDghijklmnLMNOPQRSTUVWXYZ0123o4b

434  

435 @staticmethod 

436 cdef SMResource _from_split_resource(cydriver.CUdevResource res, SMResource parent, bint is_usable): 

437 cdef SMResource self = SMResource.__new__(SMResource) 1cadefspghijklmnvuqwrtzxoyb

438 self._resource = res 1cadefspghijklmnvuqwrtzxoyb

439 self._sm_count = res.sm.smCount 1cadefspghijklmnvuqwrtzxoyb

440 IF CUDA_CORE_BUILD_MAJOR >= 13: 

441 self._min_partition_size = _fallback_if_zero( 1cadefspghijklmnvuqwrtzxoyb

442 res.sm.minSmPartitionSize, 

443 parent._min_partition_size, 

444 ) 

445 self._coscheduled_alignment = _fallback_if_zero( 1cadefspghijklmnvuqwrtzxoyb

446 res.sm.smCoscheduledAlignment, 

447 parent._coscheduled_alignment, 

448 ) 

449 self._flags = res.sm.flags 1cadefspghijklmnvuqwrtzxoyb

450 ELSE: 

451 self._min_partition_size = parent._min_partition_size 

452 self._coscheduled_alignment = parent._coscheduled_alignment 

453 self._flags = parent._flags 

454 self._is_usable = is_usable 1cadefspghijklmnvuqwrtzxoyb

455 return self 1cadefspghijklmnvuqwrtzxoyb

456  

457 @property 

458 def handle(self) -> int: 

459 """Return the address of the underlying ``CUdevResource`` struct.""" 

460 return <intptr_t>(&self._resource) 1?

461  

462 @property 

463 def sm_count(self) -> int: 

464 """Total SMs available in this resource.""" 

465 return self._sm_count 1aGFCs?vuqwrt

466  

467 @property 

468 def min_partition_size(self) -> int: 

469 """Minimum SM count required to create a partition.""" 

470 return self._min_partition_size 1as]?vwrt,*

471  

472 @property 

473 def coscheduled_alignment(self) -> int: 

474 """Number of SMs guaranteed to be co-scheduled.""" 

475 return self._coscheduled_alignment 1]?u

476  

477 @property 

478 def flags(self) -> int: 

479 """Raw flags from the underlying SM resource.""" 

480 return self._flags 1?

481  

482 def split( 

483 self, 

484 SMResourceOptions options not None: SMResourceOptions, 

485 *, 

486 bint dry_run=False 

487 ) -> tuple[list[SMResource], SMResource]: 

488 """Split this SM resource into groups and a remainder. 

489  

490 Parameters 

491 ---------- 

492 options : :obj:`SMResourceOptions` 

493 Split configuration (count, co-scheduling constraints). 

494 dry_run : bool, optional 

495 If ``True``, return filled-in metadata without creating 

496 usable resource objects. (Default to ``False``) 

497  

498 Returns 

499 ------- 

500 tuple[list[:obj:`SMResource`], :obj:`SMResource`] 

501 ``(groups, remainder)`` where each group holds a disjoint 

502 SM partition and *remainder* holds any unassigned SMs. 

503 """ 

504 cdef SMResourceOptions opts = check_or_create_options( 1cadefspghijklmnvuqwrt/:z-B,*xoyb

505 SMResourceOptions, options, "SM resource options" 

506 ) 

507 _resolve_group_count(opts) 1cadefspghijklmnvuqwrt/:z-B,*xoyb

508 _check_green_ctx_support() 1cadefspghijklmnvuqwrtzBxoyb

509 if _can_use_structured_sm_split(): 1cadefspghijklmnvuqwrtzBxoyb

510 return _split_with_general_api(self, opts, dry_run) 1cadefspghijklmnvuqwrtzBxoyb

511 # SplitByCount requires the same 12.4+ as green ctx support (already checked above) 

512 return _split_with_count_api(self, opts, dry_run) 

513  

514  

515cdef class WorkqueueResource: 

516 """Represent a workqueue resource for a device or green context. 

517  

518 Merges ``CU_DEV_RESOURCE_TYPE_WORKQUEUE_CONFIG`` and 

519 ``CU_DEV_RESOURCE_TYPE_WORKQUEUE`` under one user-facing type. 

520 Instances are returned by :obj:`DeviceResources.workqueue` and 

521 cannot be instantiated directly. 

522 """ 

523  

524 def __init__(self, *args, **kwargs) -> None: 

525 raise RuntimeError( 1@

526 "WorkqueueResource cannot be instantiated directly. " 

527 "Use dev.resources.workqueue." 

528 ) 

529  

530 @staticmethod 

531 cdef WorkqueueResource _from_dev_resources( 

532 cydriver.CUdevResource wq_config, 

533 cydriver.CUdevResource wq, 

534 ): 

535 cdef WorkqueueResource self = WorkqueueResource.__new__(WorkqueueResource) 1E8CD9!#$%'(

536 self._wq_config_resource = wq_config 1E8CD9!#$%'(

537 self._wq_resource = wq 1E8CD9!#$%'(

538 return self 1E8CD9!#$%'(

539  

540 @property 

541 def handle(self) -> int: 

542 """Return the address of the underlying config ``CUdevResource`` struct.""" 

543 return <intptr_t>(&self._wq_config_resource) 1EC.

544  

545 @property 

546 def sharing_scope(self) -> WorkqueueSharingScopeType: 

547 """Current sharing scope of this workqueue resource. 

548  

549 Returns the :class:`~cuda.core.typing.WorkqueueSharingScopeType` 

550 member corresponding to the driver-populated 

551 ``wqConfig.sharingScope`` field. It can be updated via 

552 :meth:`configure` with 

553 :attr:`WorkqueueResourceOptions.sharing_scope`. 

554 """ 

555 IF CUDA_CORE_BUILD_MAJOR >= 13: 

556 from cuda.core.typing import WorkqueueSharingScopeType 1E5H.

557 cdef object scope = self._wq_config_resource.wqConfig.sharingScope 1E5H.

558 if scope == cydriver.CUdevWorkqueueConfigScope.CU_WORKQUEUE_SCOPE_DEVICE_CTX: 1E5H.

559 return WorkqueueSharingScopeType.DEVICE_CTX 1E5.

560 elif scope == cydriver.CUdevWorkqueueConfigScope.CU_WORKQUEUE_SCOPE_GREEN_CTX_BALANCED: 1H

561 return WorkqueueSharingScopeType.GREEN_CTX_BALANCED 1H

562 raise RuntimeError(f"Unknown sharing scope enum value: {scope}") 

563 ELSE: 

564 raise RuntimeError( 

565 "WorkqueueResource requires cuda.core to be built with CUDA 13.x bindings" 

566 ) 

567  

568 @property 

569 def concurrency_limit(self) -> int: 

570 """Current expected maximum concurrent stream-ordered workloads. 

571  

572 Reflects the driver-populated ``wqConfig.wqConcurrencyLimit`` field. 

573 When first queried from a device, this matches the driver-reported 

574 cap (typically ``CUDA_DEVICE_MAX_CONNECTIONS``). It can be updated 

575 via :meth:`configure` with 

576 :attr:`WorkqueueResourceOptions.concurrency_limit`. 

577 """ 

578 IF CUDA_CORE_BUILD_MAJOR >= 13: 

579 return self._wq_config_resource.wqConfig.wqConcurrencyLimit 1E7.

580 ELSE: 

581 raise RuntimeError( 

582 "WorkqueueResource requires cuda.core to be built with CUDA 13.x bindings" 

583 ) 

584  

585 @property 

586 def device(self) -> Device: 

587 """The :class:`~cuda.core.Device` this workqueue resource is available on.""" 

588 IF CUDA_CORE_BUILD_MAJOR >= 13: 

589 from cuda.core._device import Device # avoid circular import 1E.

590 return Device(int(self._wq_config_resource.wqConfig.device)) 1E.

591 ELSE: 

592 raise RuntimeError( 

593 "WorkqueueResource requires cuda.core to be built with CUDA 13.x bindings" 

594 ) 

595  

596 def configure(self, WorkqueueResourceOptions options not None: WorkqueueResourceOptions) -> None: 

597 """Configure the workqueue resource in place. 

598  

599 Parameters 

600 ---------- 

601 options : :obj:`WorkqueueResourceOptions` 

602 Configuration options (sharing scope, concurrency limit). 

603 """ 

604 cdef WorkqueueResourceOptions opts = check_or_create_options( 1p67+5H)

605 WorkqueueResourceOptions, options, "Workqueue resource options" 

606 ) 

607 _check_green_ctx_support() 1p67+5H)

608 _check_workqueue_support() 1p67+5H)

609 if opts.sharing_scope is None and opts.concurrency_limit is None: 1p67+5H)

610 return None 1+

611  

612 IF CUDA_CORE_BUILD_MAJOR >= 13: 

613 if opts.concurrency_limit is not None: 1p675H)

614 self._wq_config_resource.wqConfig.wqConcurrencyLimit = ( 1p67

615 <unsigned int>opts.concurrency_limit 1p67

616 ) 

617 if opts.sharing_scope == "device_ctx": 1p675H)

618 self._wq_config_resource.wqConfig.sharingScope = ( 15

619 cydriver.CUdevWorkqueueConfigScope.CU_WORKQUEUE_SCOPE_DEVICE_CTX 

620 ) 

621 elif opts.sharing_scope == "green_ctx_balanced": 1p67H)

622 self._wq_config_resource.wqConfig.sharingScope = ( 1p6H)

623 cydriver.CUdevWorkqueueConfigScope.CU_WORKQUEUE_SCOPE_GREEN_CTX_BALANCED 

624 ) 

625 ELSE: 

626 raise RuntimeError( 

627 "WorkqueueResource requires cuda.core to be built with CUDA 13.x bindings" 

628 ) 

629  

630  

631cdef class DeviceResources: 

632 """Namespace for hardware resource queries. 

633  

634 When obtained via :obj:`Device.resources`, queries return full device 

635 resources. When obtained via :obj:`Context.resources` or 

636 :obj:`Stream.resources`, queries return the resources provisioned for 

637 that context. 

638  

639 This class cannot be instantiated directly. 

640 """ 

641  

642 def __init__(self, *args, **kwargs) -> None: 

643 raise RuntimeError( 1@

644 "DeviceResources cannot be instantiated directly. " 

645 "Use dev.resources or ctx.resources." 

646 ) 

647  

648 @staticmethod 

649 cdef DeviceResources _init(int device_id): 

650 cdef DeviceResources self = DeviceResources.__new__(DeviceResources) 1cIdJ8efKDghijklmnLMNOPQRSTUVWXYZ0129!#$%'(3o4b

651 self._device_id = device_id 1cIdJ8efKDghijklmnLMNOPQRSTUVWXYZ0129!#$%'(3o4b

652 # _h_context is default empty — queries use cuDeviceGetDevResource 

653 return self 1cIdJ8efKDghijklmnLMNOPQRSTUVWXYZ0129!#$%'(3o4b

654  

655 @staticmethod 

656 cdef DeviceResources _init_from_ctx(ContextHandle h_context, int device_id): 

657 cdef DeviceResources self = DeviceResources.__new__(DeviceResources) 1aGFEC

658 self._device_id = device_id 1aGFEC

659 self._h_context = h_context 1aGFEC

660 return self 1aGFEC

661  

662 cdef inline int _query_sm(self, cydriver.CUdevResource* res) except?-1 nogil: 

663 """Query SM resource from either device or context.""" 

664 cdef GreenCtxHandle h_green 

665 if self._h_context: 1caIGdFJCefKDghijklmnLMNOPQRSTUVWXYZ0123o4b

666 h_green = get_context_green_ctx(self._h_context) 1aGFC

667 if h_green: 1aGFC

668 HANDLE_RETURN(cydriver.cuGreenCtxGetDevResource( 1aGC

669 as_cu(h_green), res, 

670 cydriver.CUdevResourceType.CU_DEV_RESOURCE_TYPE_SM, 

671 )) 

672 else: 

673 HANDLE_RETURN(cydriver.cuCtxGetDevResource( 1F

674 as_cu(self._h_context), res, 

675 cydriver.CUdevResourceType.CU_DEV_RESOURCE_TYPE_SM, 1F

676 )) 

677 else: 

678 HANDLE_RETURN(cydriver.cuDeviceGetDevResource( 1cIdJefKDghijklmnLMNOPQRSTUVWXYZ0123o4b

679 <cydriver.CUdevice>(self._device_id), res, 

680 cydriver.CUdevResourceType.CU_DEV_RESOURCE_TYPE_SM, 1cIdJefKDghijklmnLMNOPQRSTUVWXYZ0123o4b

681 )) 

682 return 0 1caIGdFJCefKDghijklmnLMNOPQRSTUVWXYZ0123o4b

683  

684 @property 

685 def sm(self) -> SMResource: 

686 """Return the :obj:`SMResource` for this device or context.""" 

687 _check_green_ctx_support() 1caIGdFJCefKDghijklmnLMNOPQRSTUVWXYZ0123o4b

688 cdef cydriver.CUdevResource res 

689 with nogil: 1caIGdFJCefKDghijklmnLMNOPQRSTUVWXYZ0123o4b

690 self._query_sm(&res) 1caIGdFJCefKDghijklmnLMNOPQRSTUVWXYZ0123o4b

691 return SMResource._from_dev_resource(res, self._device_id) 1caIGdFJCefKDghijklmnLMNOPQRSTUVWXYZ0123o4b

692  

693 @property 

694 def workqueue(self) -> WorkqueueResource: 

695 """Return the :obj:`WorkqueueResource` for this device or context.""" 

696 _check_green_ctx_support() 1E8CD9!#$%'(

697 _check_workqueue_support() 1E8CD9!#$%'(

698 cdef cydriver.CUdevResource _wq_config 

699 cdef cydriver.CUdevResource _wq 

700  

701 IF CUDA_CORE_BUILD_MAJOR >= 13: 

702 cdef GreenCtxHandle h_green 

703 if self._h_context: 1E8CD9!#$%'(

704 h_green = get_context_green_ctx(self._h_context) 1EC

705 if h_green: 1EC

706 # Green context query 

707 with nogil: 1C

708 HANDLE_RETURN(cydriver.cuGreenCtxGetDevResource( 1C

709 as_cu(h_green), 

710 &_wq_config, 

711 cydriver.CUdevResourceType.CU_DEV_RESOURCE_TYPE_WORKQUEUE_CONFIG, 

712 )) 

713 HANDLE_RETURN(cydriver.cuGreenCtxGetDevResource( 1C

714 as_cu(h_green), 

715 &_wq, 

716 cydriver.CUdevResourceType.CU_DEV_RESOURCE_TYPE_WORKQUEUE, 

717 )) 

718 else: 

719 # Primary context query 

720 with nogil: 1E

721 HANDLE_RETURN(cydriver.cuCtxGetDevResource( 1E

722 as_cu(self._h_context), 

723 &_wq_config, 

724 cydriver.CUdevResourceType.CU_DEV_RESOURCE_TYPE_WORKQUEUE_CONFIG, 

725 )) 

726 HANDLE_RETURN(cydriver.cuCtxGetDevResource( 1E

727 as_cu(self._h_context), 

728 &_wq, 

729 cydriver.CUdevResourceType.CU_DEV_RESOURCE_TYPE_WORKQUEUE, 

730 )) 

731 else: 

732 # Device-level query 

733 with nogil: 18D9!#$%'(

734 HANDLE_RETURN(cydriver.cuDeviceGetDevResource( 18D9!#$%'(

735 <cydriver.CUdevice>(self._device_id), 

736 &_wq_config, 

737 cydriver.CUdevResourceType.CU_DEV_RESOURCE_TYPE_WORKQUEUE_CONFIG, 

738 )) 

739 HANDLE_RETURN(cydriver.cuDeviceGetDevResource( 18D9!#$%'(

740 <cydriver.CUdevice>(self._device_id), 

741 &_wq, 

742 cydriver.CUdevResourceType.CU_DEV_RESOURCE_TYPE_WORKQUEUE, 

743 )) 

744 return WorkqueueResource._from_dev_resources(_wq_config, _wq) 1E8CD9!#$%'(

745 ELSE: 

746 raise RuntimeError( 

747 "WorkqueueResource requires cuda.core to be built with CUDA 13.x bindings" 

748 )