Skip to content

Commit 4d1ddb4

Browse files
committed
Fix NVIDIA#1995: Use StrEnum for enum-like strings
1 parent ecd558a commit 4d1ddb4

17 files changed

Lines changed: 357 additions & 149 deletions

‎cuda_core/cuda/core/_linker.pyx‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ from cuda.core._utils.cuda_utils import (
3939
driver,
4040
is_sequence,
4141
)
42+
from cuda.core.typing import CompilerBackend
4243

4344
ctypedef const char* const_char_ptr
4445
ctypedef void* void_ptr
@@ -70,12 +71,12 @@ cdef class Linker:
7071
def __init__(self, *object_codes: ObjectCode, options: "LinkerOptions" = None):
7172
Linker_init(self, object_codes, options)
7273

73-
def link(self, target_type) -> ObjectCode:
74+
def link(self, target_type: ObjectCodeFormat | str) -> ObjectCode:
7475
"""Link the provided object codes into a single output of the specified target type.
7576

7677
Parameters
7778
----------
78-
target_type : str
79+
target_type : ObjectCodeFormat | str
7980
The type of the target output. Must be either "cubin" or "ptx".
8081

8182
Returns
@@ -88,7 +89,7 @@ cdef class Linker:
8889
Ensure that input object codes were compiled with appropriate
8990
flags for linking (e.g., relocatable device code enabled).
9091
"""
91-
return Linker_link(self, target_type)
92+
return Linker_link(self, str(target_type))
9293

9394
def get_error_log(self) -> str:
9495
"""Get the error log generated by the linker.
@@ -168,9 +169,9 @@ cdef class Linker:
168169
return as_py(self._culink_handle)
169170

170171
@property
171-
def backend(self) -> str:
172-
"""Return this Linker instance's underlying backend."""
173-
return "nvJitLink" if self._use_nvjitlink else "driver"
172+
def backend(self) -> CompilerBackend:
173+
"""Return this Linker instance's underlying :class:`CompilerBackend`."""
174+
return CompilerBackend.NVJITLINK if self._use_nvjitlink else CompilerBackend.DRIVER
174175

175176

176177
# =============================================================================

‎cuda_core/cuda/core/_memory/_managed_memory_resource.pyx‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@ from dataclasses import dataclass
1616
import threading
1717
import warnings
1818

19+
from cuda.core.typing import ManagedMemoryLocationType
20+
1921
__all__ = ['ManagedMemoryResource', 'ManagedMemoryResourceOptions']
2022

2123

@@ -30,7 +32,7 @@ cdef class ManagedMemoryResourceOptions:
3032
meaning depends on ``preferred_location_type``.
3133
(Default to ``None``)
3234
33-
preferred_location_type : ``"device"`` | ``"host"`` | ``"host_numa"`` | None, optional
35+
preferred_location_type : ManagedMemoryLocationType | str | None, optional
3436
Controls how ``preferred_location`` is interpreted.
3537
3638
When set to ``None`` (the default), legacy behavior is used:
@@ -54,7 +56,7 @@ cdef class ManagedMemoryResourceOptions:
5456
(Default to ``None``)
5557
"""
5658
preferred_location: int | None = None
57-
preferred_location_type: str | None = None
59+
preferred_location_type: ManagedMemoryLocationType | str | None = None
5860

5961

6062
cdef class ManagedMemoryResource(_MemPool):
@@ -97,7 +99,7 @@ cdef class ManagedMemoryResource(_MemPool):
9799
return -1
98100

99101
@property
100-
def preferred_location(self) -> tuple | None:
102+
def preferred_location(self) -> tuple[ManagedMemoryLocationType, int | None] | None:
101103
"""The preferred location for managed memory allocations.
102104

103105
Returns ``None`` if no preferred location is set (driver decides),
@@ -108,8 +110,8 @@ cdef class ManagedMemoryResource(_MemPool):
108110
if self._pref_loc_type is None:
109111
return None
110112
if self._pref_loc_type == "host":
111-
return ("host", None)
112-
return (self._pref_loc_type, self._pref_loc_id)
113+
return (ManagedMemoryLocationType.HOST, None)
114+
return (ManagedMemoryLocationType(self._pref_loc_type), self._pref_loc_id)
113115

114116
@property
115117
def is_device_accessible(self) -> bool:

‎cuda_core/cuda/core/_memory/_virtual_memory_resource.py‎

Lines changed: 37 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
1-
# SPDX-FileCopyrightText: Copyright (c) 2024-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
1+
# SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
22
#
33
# SPDX-License-Identifier: Apache-2.0
44

55
from __future__ import annotations
66

77
from dataclasses import dataclass, field
8-
from typing import TYPE_CHECKING, Iterable, Literal
8+
from typing import TYPE_CHECKING, Iterable
99

1010
if TYPE_CHECKING:
1111
from cuda.core._stream import Stream
@@ -21,15 +21,16 @@
2121
_check_driver_error as raise_if_driver_error,
2222
)
2323
from cuda.core._utils.version import binding_version
24+
from cuda.core.typing import (
25+
VirtualMemoryAccessType,
26+
VirtualMemoryAllocationType,
27+
VirtualMemoryGranularityType,
28+
VirtualMemoryHandleType,
29+
VirtualMemoryLocationType,
30+
)
2431

2532
__all__ = ["VirtualMemoryResource", "VirtualMemoryResourceOptions"]
2633

27-
VirtualMemoryHandleTypeT = Literal["posix_fd", "generic", "win32_kmt", "fabric"] | None
28-
VirtualMemoryLocationTypeT = Literal["device", "host", "host_numa", "host_numa_current"]
29-
VirtualMemoryGranularityT = Literal["minimum", "recommended"]
30-
VirtualMemoryAccessTypeT = Literal["rw", "r"] | None
31-
VirtualMemoryAllocationTypeT = Literal["pinned", "managed"]
32-
3334

3435
@dataclass
3536
class VirtualMemoryResourceOptions:
@@ -38,69 +39,72 @@ class VirtualMemoryResourceOptions:
3839
3940
Attributes
4041
----------
41-
allocation_type: :obj:`~_memory.VirtualMemoryAllocationTypeT`
42+
allocation_type: :obj:`~_memory.VirtualMemoryAllocationType` | str
4243
Controls the type of allocation.
43-
location_type: :obj:`~_memory.VirtualMemoryLocationTypeT`
44+
location_type: :obj:`~_memory.VirtualMemoryLocationType` | str
4445
Controls the location of the allocation.
45-
handle_type: :obj:`~_memory.VirtualMemoryHandleTypeT`
46+
handle_type: :obj:`~_memory.VirtualMemoryHandleType` | str
4647
Export handle type for the physical allocation. Use
4748
``"posix_fd"`` on Linux if you plan to
4849
import/export the allocation (required for cuMemRetainAllocationHandle).
4950
Use `None` if you don't need an exportable handle.
5051
gpu_direct_rdma: bool
5152
Hint that the allocation should be GDR-capable (if supported).
52-
granularity: :obj:`~_memory.VirtualMemoryGranularityT`
53+
granularity: :obj:`~_memory.VirtualMemoryGranularityType` | str
5354
Controls granularity query and size rounding.
5455
addr_hint: int
5556
A (optional) virtual address hint to try to reserve at. Setting it to 0 lets the CUDA driver decide.
5657
addr_align: int
5758
Alignment for the VA reservation. If `None`, use the queried granularity.
5859
peers: Iterable[int]
5960
Extra device IDs that should be granted access in addition to ``device``.
60-
self_access: :obj:`~_memory.VirtualMemoryAccessTypeT`
61+
self_access: :obj:`~_memory.VirtualMemoryAccessType` | None | str
6162
Access flags for the owning device.
62-
peer_access: :obj:`~_memory.VirtualMemoryAccessTypeT`
63+
peer_access: :obj:`~_memory.VirtualMemoryAccessType` | None | str
6364
Access flags for peers.
6465
"""
6566

66-
# Human-friendly strings; normalized in __post_init__
67-
allocation_type: VirtualMemoryAllocationTypeT = "pinned"
68-
location_type: VirtualMemoryLocationTypeT = "device"
69-
handle_type: VirtualMemoryHandleTypeT = "posix_fd"
70-
granularity: VirtualMemoryGranularityT = "recommended"
67+
allocation_type: VirtualMemoryAllocationType = VirtualMemoryAllocationType.PINNED
68+
location_type: VirtualMemoryLocationType = VirtualMemoryLocationType.DEVICE
69+
handle_type: VirtualMemoryHandleType = VirtualMemoryHandleType.POSIX_FD
70+
granularity: VirtualMemoryGranularityType = VirtualMemoryGranularityType.RECOMMENDED
7171
gpu_direct_rdma: bool = False
7272
addr_hint: int | None = 0
7373
addr_align: int | None = None
7474
peers: Iterable[int] = field(default_factory=tuple)
75-
self_access: VirtualMemoryAccessTypeT = "rw"
76-
peer_access: VirtualMemoryAccessTypeT = "rw"
75+
self_access: VirtualMemoryAccessType = VirtualMemoryAccessType.READ_WRITE
76+
peer_access: VirtualMemoryAccessType = VirtualMemoryAccessType.READ_WRITE
7777

7878
_a = driver.CUmemAccess_flags
79-
_access_flags = {"rw": _a.CU_MEM_ACCESS_FLAGS_PROT_READWRITE, "r": _a.CU_MEM_ACCESS_FLAGS_PROT_READ, None: 0} # noqa: RUF012
79+
_access_flags = { # noqa: RUF012
80+
VirtualMemoryAccessType.READ_WRITE: _a.CU_MEM_ACCESS_FLAGS_PROT_READWRITE,
81+
VirtualMemoryAccessType.READ: _a.CU_MEM_ACCESS_FLAGS_PROT_READ,
82+
None: 0,
83+
}
8084
_h = driver.CUmemAllocationHandleType
8185
_handle_types = { # noqa: RUF012
8286
None: _h.CU_MEM_HANDLE_TYPE_NONE,
83-
"posix_fd": _h.CU_MEM_HANDLE_TYPE_POSIX_FILE_DESCRIPTOR,
84-
"win32_kmt": _h.CU_MEM_HANDLE_TYPE_WIN32_KMT,
85-
"fabric": _h.CU_MEM_HANDLE_TYPE_FABRIC,
87+
VirtualMemoryHandleType.POSIX_FD: _h.CU_MEM_HANDLE_TYPE_POSIX_FILE_DESCRIPTOR,
88+
VirtualMemoryHandleType.WIN32_KMT: _h.CU_MEM_HANDLE_TYPE_WIN32_KMT,
89+
VirtualMemoryHandleType.FABRIC: _h.CU_MEM_HANDLE_TYPE_FABRIC,
8690
}
8791
_g = driver.CUmemAllocationGranularity_flags
8892
_granularity = { # noqa: RUF012
89-
"recommended": _g.CU_MEM_ALLOC_GRANULARITY_RECOMMENDED,
90-
"minimum": _g.CU_MEM_ALLOC_GRANULARITY_MINIMUM,
93+
VirtualMemoryGranularityType.RECOMMENDED: _g.CU_MEM_ALLOC_GRANULARITY_RECOMMENDED,
94+
VirtualMemoryGranularityType.MINIMUM: _g.CU_MEM_ALLOC_GRANULARITY_MINIMUM,
9195
}
9296
_l = driver.CUmemLocationType
9397
_location_type = { # noqa: RUF012
94-
"device": _l.CU_MEM_LOCATION_TYPE_DEVICE,
95-
"host": _l.CU_MEM_LOCATION_TYPE_HOST,
96-
"host_numa": _l.CU_MEM_LOCATION_TYPE_HOST_NUMA,
97-
"host_numa_current": _l.CU_MEM_LOCATION_TYPE_HOST_NUMA_CURRENT,
98+
VirtualMemoryLocationType.DEVICE: _l.CU_MEM_LOCATION_TYPE_DEVICE,
99+
VirtualMemoryLocationType.HOST: _l.CU_MEM_LOCATION_TYPE_HOST,
100+
VirtualMemoryLocationType.HOST_NUMA: _l.CU_MEM_LOCATION_TYPE_HOST_NUMA,
101+
VirtualMemoryLocationType.HOST_NUMA_CURRENT: _l.CU_MEM_LOCATION_TYPE_HOST_NUMA_CURRENT,
98102
}
99103
_t = driver.CUmemAllocationType
100104
# CUDA 13+ exposes MANAGED in CUmemAllocationType; older 12.x does not
101-
_allocation_type = {"pinned": _t.CU_MEM_ALLOCATION_TYPE_PINNED} # noqa: RUF012
105+
_allocation_type = {VirtualMemoryAllocationType.PINNED: _t.CU_MEM_ALLOCATION_TYPE_PINNED} # noqa: RUF012
102106
if binding_version() >= (13, 0, 0):
103-
_allocation_type["managed"] = _t.CU_MEM_ALLOCATION_TYPE_MANAGED
107+
_allocation_type[VirtualMemoryAllocationType.MANAGED] = _t.CU_MEM_ALLOCATION_TYPE_MANAGED
104108

105109
@staticmethod
106110
def _access_to_flags(spec: str):

‎cuda_core/cuda/core/_module.pyx‎

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ from cuda.core._device import Device
1212
from cuda.core._launch_config cimport LaunchConfig
1313
from cuda.core._launch_config import LaunchConfig
1414
from cuda.core._stream cimport Stream
15+
from cuda.core._program import ObjectCodeFormat
1516
from cuda.core._resource_handles cimport (
1617
LibraryHandle,
1718
KernelHandle,
@@ -569,7 +570,7 @@ cdef class Kernel:
569570

570571
CodeTypeT = bytes | bytearray | str
571572

572-
cdef tuple _supported_code_type = ("cubin", "ptx", "ltoir", "fatbin", "object", "library")
573+
cdef tuple _supported_code_type = tuple(ObjectCodeFormat.__members__.values())
573574

574575
cdef class ObjectCode:
575576
"""Represent a compiled program to be loaded onto the device.
@@ -599,7 +600,7 @@ cdef class ObjectCode:
599600
# _h_library is assigned during _lazy_load_module
600601
self._h_library = LibraryHandle() # Empty handle
601602

602-
self._code_type = code_type
603+
self._code_type = str(code_type)
603604
self._module = module
604605
self._sym_map = {} if symbol_mapping is None else symbol_mapping
605606
self._name = name if name else ""
@@ -629,7 +630,7 @@ cdef class ObjectCode:
629630
should be mapped to the mangled names before trying to retrieve
630631
them (default to no mappings).
631632
"""
632-
return ObjectCode._init(module, "cubin", name=name, symbol_mapping=symbol_mapping)
633+
return ObjectCode._init(module, ObjectCodeFormat.CUBIN, name=name, symbol_mapping=symbol_mapping)
633634

634635
@staticmethod
635636
def from_ptx(module: bytes | str, *, name: str = "", symbol_mapping: dict | None = None) -> ObjectCode:
@@ -647,7 +648,7 @@ cdef class ObjectCode:
647648
should be mapped to the mangled names before trying to retrieve
648649
them (default to no mappings).
649650
"""
650-
return ObjectCode._init(module, "ptx", name=name, symbol_mapping=symbol_mapping)
651+
return ObjectCode._init(module, ObjectCodeFormat.PTX, name=name, symbol_mapping=symbol_mapping)
651652

652653
@staticmethod
653654
def from_ltoir(module: bytes | str, *, name: str = "", symbol_mapping: dict | None = None) -> ObjectCode:
@@ -665,7 +666,7 @@ cdef class ObjectCode:
665666
should be mapped to the mangled names before trying to retrieve
666667
them (default to no mappings).
667668
"""
668-
return ObjectCode._init(module, "ltoir", name=name, symbol_mapping=symbol_mapping)
669+
return ObjectCode._init(module, ObjectCodeFormat.LTOIR, name=name, symbol_mapping=symbol_mapping)
669670

670671
@staticmethod
671672
def from_fatbin(module: bytes | str, *, name: str = "", symbol_mapping: dict | None = None) -> ObjectCode:
@@ -683,7 +684,7 @@ cdef class ObjectCode:
683684
should be mapped to the mangled names before trying to retrieve
684685
them (default to no mappings).
685686
"""
686-
return ObjectCode._init(module, "fatbin", name=name, symbol_mapping=symbol_mapping)
687+
return ObjectCode._init(module, ObjectCodeFormat.FATBIN, name=name, symbol_mapping=symbol_mapping)
687688

688689
@staticmethod
689690
def from_object(module: bytes | str, *, name: str = "", symbol_mapping: dict | None = None) -> ObjectCode:
@@ -701,7 +702,7 @@ cdef class ObjectCode:
701702
should be mapped to the mangled names before trying to retrieve
702703
them (default to no mappings).
703704
"""
704-
return ObjectCode._init(module, "object", name=name, symbol_mapping=symbol_mapping)
705+
return ObjectCode._init(module, ObjectCodeFormat.OBJECT, name=name, symbol_mapping=symbol_mapping)
705706

706707
@staticmethod
707708
def from_library(module: bytes | str, *, name: str = "", symbol_mapping: dict | None = None) -> ObjectCode:
@@ -719,7 +720,7 @@ cdef class ObjectCode:
719720
should be mapped to the mangled names before trying to retrieve
720721
them (default to no mappings).
721722
"""
722-
return ObjectCode._init(module, "library", name=name, symbol_mapping=symbol_mapping)
723+
return ObjectCode._init(module, ObjectCodeFormat.LIBRARY, name=name, symbol_mapping=symbol_mapping)
723724

724725
# TODO: do we want to unload in a finalizer? Probably not..
725726

@@ -758,7 +759,7 @@ cdef class ObjectCode:
758759

759760
"""
760761
self._lazy_load_module()
761-
supported_code_types = ("cubin", "ptx", "fatbin")
762+
supported_code_types = (ObjectCodeFormat.CUBIN, ObjectCodeFormat.PTX, ObjectCodeFormat.FATBIN)
762763
if self._code_type not in supported_code_types:
763764
raise RuntimeError(f'Unsupported code type "{self._code_type}" ({supported_code_types=})')
764765
try:

0 commit comments

Comments
 (0)