Skip to content

Commit 35983fa

Browse files
committed
cuda.core: replace library asserts with explicit errors
python -O strips assert statements, and Cython drops them too, so the checks they carried vanished in optimized runs. Values that come from a caller, a DLPack or CUDA Array Interface producer, or an NVML payload now raise ValueError or TypeError naming the value. Internal invariants raise RuntimeError("internal cuda.core error, please report: ..."). The unmatched-capsule branch in view_as_dlpack was an assert False, but a producer reaches it by returning anything other than an unconsumed DLPack capsule, so it raises ValueError rather than the internal error. Enforce ruff S101 for cuda_core/cuda/core only. Enabling it for everything outside tests would flag about 180 asserts in pathfinder, the samples and the shared test helpers. The two asserts in _memory/_ipc.pyx are handled by #2704.
1 parent a2fb804 commit 35983fa

18 files changed

Lines changed: 106 additions & 17 deletions

‎cuda_core/cuda/core/_device.pyx‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1684,7 +1684,11 @@ cdef inline int Device_resolve_device_id(device_id) except? -1:
16841684
elif err == cydriver.CUresult.CUDA_ERROR_INVALID_CONTEXT:
16851685
with nogil:
16861686
HANDLE_RETURN(cydriver.cuCtxGetCurrent(&ctx))
1687-
assert <void*>(ctx) == NULL
1687+
if <void*>(ctx) != NULL:
1688+
raise RuntimeError(
1689+
"internal cuda.core error, please report: cuCtxGetDevice returned "
1690+
"CUDA_ERROR_INVALID_CONTEXT while a context is current"
1691+
)
16881692
return 0 # cudart behavior
16891693
else:
16901694
HANDLE_RETURN(err)

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -276,7 +276,8 @@ def accessed_by(self, locations: Iterable[Device | Host]) -> None:
276276
target.add(loc)
277277
for loc in target:
278278
spec = _coerce_location(loc)
279-
assert spec is not None
279+
if spec is None:
280+
raise RuntimeError(f"internal cuda.core error, please report: no location spec for {loc!r}")
280281
if spec.kind not in ("device", "host"):
281282
raise ValueError(f"advise {_SET_ACCESSED_BY.name} does not support location_type='{spec.kind}'")
282283
current = set(_query_accessed_by(self))

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,8 @@ cdef class ManagedMemoryResource(_MemPool):
122122
(``prefetch``, ``discard``, ``discard_prefetch``).
123123
"""
124124
MP_check_open(self)
125-
assert isinstance(stream, Stream), "Only Stream is supported for managed memory allocations"
125+
if not isinstance(stream, Stream):
126+
raise TypeError(f"Only Stream is supported for managed memory allocations, got {type(stream).__name__}")
126127
if self.is_mapped:
127128
raise TypeError("Cannot allocate from a mapped IPC-enabled memory resource")
128129
cdef Stream s = Stream_accept(stream)

‎cuda_core/cuda/core/_memoryview.pyx‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1040,14 +1040,17 @@ cdef StridedMemoryView view_as_dlpack(obj, stream_ptr, view=None):
10401040
stream_ptr = int(stream_ptr)
10411041
dldevice, device_id = obj.__dlpack_device__()
10421042
if dldevice == _kDLCPU:
1043-
assert device_id == 0
1043+
if device_id != 0:
1044+
raise ValueError(f"__dlpack_device__() reported device_id {device_id} for a kDLCPU tensor; expected 0")
10441045
device_id = -1
10451046
if stream_ptr is None:
10461047
raise BufferError("stream=None is ambiguous with view()")
10471048
elif stream_ptr == -1:
10481049
stream_ptr = None
10491050
elif dldevice == _kDLCUDA:
1050-
assert device_id >= 0
1051+
if device_id < 0:
1052+
raise ValueError(
1053+
f"__dlpack_device__() reported device_id {device_id} for a kDLCUDA tensor; expected 0 or more")
10511054
is_device_accessible = True
10521055
# no need to check other stream values, it's a pass-through
10531056
if stream_ptr is None:
@@ -1090,7 +1093,7 @@ cdef StridedMemoryView view_as_dlpack(obj, stream_ptr, view=None):
10901093
is_readonly = False
10911094
used_name = DLPACK_TENSOR_USED_NAME
10921095
else:
1093-
assert False
1096+
raise ValueError(f"__dlpack__() returned {capsule!r}, not an unconsumed DLPack capsule")
10941097
10951098
cpython.PyCapsule_SetName(capsule, used_name)
10961099
@@ -1214,7 +1217,9 @@ cpdef StridedMemoryView view_as_cai(obj, stream_ptr, view=None):
12141217
if stream is not None:
12151218
producer_s = <intptr_t>(stream)
12161219
consumer_s = <intptr_t>(stream_ptr)
1217-
assert producer_s > 0
1220+
if producer_s <= 0:
1221+
raise ValueError(
1222+
f"__cuda_array_interface__ reported stream {stream}; expected None or a positive stream handle")
12181223
# establish stream order
12191224
if producer_s != consumer_s:
12201225
with nogil:

‎cuda_core/cuda/core/_module.pyx‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -632,7 +632,8 @@ cdef class ObjectCode:
632632

633633
@classmethod
634634
def _init(cls, module, code_type, *, name: str = "", symbol_mapping: dict[str, str] | None = None) -> ObjectCode:
635-
assert code_type in _supported_code_type, f"{code_type=} is not supported"
635+
if code_type not in _supported_code_type:
636+
raise ValueError(f"{code_type=} is not supported")
636637
cdef ObjectCode self = ObjectCode.__new__(ObjectCode)
637638

638639
# _h_library is assigned during _lazy_load_module

‎cuda_core/cuda/core/_program.pyx‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1359,7 +1359,8 @@ cdef inline object _prepare_nvvm_options_impl(object opts, bint as_bytes):
13591359
options = []
13601360

13611361
# Options supported by NVVM
1362-
assert opts.arch is not None
1362+
if opts.arch is None:
1363+
raise RuntimeError("internal cuda.core error, please report: ProgramOptions.arch is None")
13631364
arch = opts.arch
13641365
if arch.startswith("sm_"):
13651366
arch = f"compute_{arch[3:]}"

‎cuda_core/cuda/core/system/_device.pyx‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -43,9 +43,8 @@ if TYPE_CHECKING:
4343
cdef object _pstate_to_int(object pstate):
4444
if pstate == nvml.Pstates.PSTATE_UNKNOWN:
4545
return None
46-
assert (
47-
int(pstate) >= 0 and int(pstate) <= 15
48-
), f"Invalid P-state: {pstate}. Must be between 0 and 15 inclusive, or PSTATE_UNKNOWN."
46+
if int(pstate) < 0 or int(pstate) > 15:
47+
raise ValueError(f"Invalid P-state: {pstate}. Must be between 0 and 15 inclusive, or PSTATE_UNKNOWN.")
4948
return int(pstate) - int(nvml.Pstates.PSTATE_0)
5049

5150

‎cuda_core/cuda/core/system/_field_values.pxi‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,8 @@ cdef class FieldValue:
1212
cdef object _field_value
1313

1414
def __init__(self, field_value: nvml.FieldValue):
15-
assert len(field_value) == 1
15+
if len(field_value) != 1:
16+
raise ValueError(f"FieldValue expects exactly one field value, got {len(field_value)}")
1617
self._field_value = field_value
1718

1819
@property

‎cuda_core/cuda/core/system/_system_events.pyx‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,8 @@ cdef class SystemEvent:
4040
cdef object _event_data
4141

4242
def __init__(self, event_data not None: nvml.SystemEventData_v1):
43-
assert len(event_data) == 1
43+
if len(event_data) != 1:
44+
raise ValueError(f"SystemEvent expects exactly one event, got {len(event_data)}")
4445
self._event_data = event_data
4546

4647
@property

‎cuda_core/cuda/core/utils/_program_cache/_file_stream.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,8 @@ def _with_sharing_retry(
9393
last_exc = exc
9494
if on_exhausted is not None:
9595
return on_exhausted(last_exc)
96-
assert last_exc is not None # at least one iteration ran and caught a PermissionError
96+
if last_exc is None:
97+
raise RuntimeError("internal cuda.core error, please report: sharing retry ran no attempts")
9798
raise last_exc
9899

99100

0 commit comments

Comments
 (0)