Coverage for cuda/bindings/_v2/nvrtc.pyx: 57.78%
450 statements
« prev ^ index » next coverage.py v7.18.0, created at 2026-12-03 01:06 +0000
« prev ^ index » next coverage.py v7.18.0, created at 2026-12-03 01:06 +0000
1# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2#
3# SPDX-License-Identifier: Apache-2.0
4#
5# This code was automatically generated across versions from 12.9.0 to 13.5.0. Do not modify it directly.
6# CYTHON-BINDINGS-GENERATED-DO-NOT-MODIFY-THIS-FILE: format=1; content-sha256=fff85c453c84fc538b768c24c857213e2dbe1ffb80a2a2e2838019d7e7d1630d
9# <<<< PREAMBLE CONTENT >>>>
11cimport cpython as _cyb_cpython
12cimport cpython.buffer as _cyb_cpython_buffer
13from cpython.buffer cimport (
14 PyBUF_SIMPLE as _cyb_PyBUF_SIMPLE,
15 PyBuffer_Release as _cyb_PyBuffer_Release,
16 PyObject_GetBuffer as _cyb_PyObject_GetBuffer,
17 Py_buffer as _cyb_Py_buffer,
18)
19from cython cimport view as _cyb_view
20from libc.stdint cimport intptr_t
21from libc.stdlib cimport (
22 calloc as _cyb_calloc,
23 free as _cyb_free,
24)
25from libc.string cimport (
26 memcmp as _cyb_memcmp,
27 memcpy as _cyb_memcpy,
28 memmove as _cyb_memmove,
29)
31from cuda.bindings._internal._fast_enum import FastEnum as _cyb_FastEnum
33import numpy as _numpy
35cdef _cyb___getbuffer(object self, _cyb_cpython.Py_buffer *buffer, void *ptr, int size, bint readonly):
36 buffer.buf = <char *>ptr
37 buffer.format = 'b'
38 buffer.internal = NULL
39 buffer.itemsize = 1
40 buffer.len = size
41 buffer.ndim = 1
42 buffer.obj = self
43 buffer.readonly = readonly
44 buffer.shape = &buffer.len
45 buffer.strides = &buffer.itemsize
46 buffer.suboffsets = NULL
48cdef _cyb_from_buffer(buffer, size, lowpp_type):
49 cdef _cyb_cpython.Py_buffer view
50 if _cyb_cpython.PyObject_GetBuffer(buffer, &view, _cyb_cpython_buffer.PyBUF_SIMPLE) != 0:
51 raise TypeError("buffer argument does not support the buffer protocol")
52 try:
53 if view.itemsize != 1:
54 raise ValueError("buffer itemsize must be 1 byte")
55 if view.len != size:
56 raise ValueError(f"buffer length must be {size} bytes")
57 return lowpp_type.from_ptr(<intptr_t><void *>view.buf, view.readonly != 0, buffer)
58 finally:
59 _cyb_cpython.PyBuffer_Release(&view)
61cdef _cyb_from_data(data, dtype_name, expected_dtype, lowpp_type):
62 # _numpy.recarray is a subclass of _numpy.ndarray, so implicitly handled here.
63 if isinstance(data, lowpp_type):
64 return data
65 if not isinstance(data, _numpy.ndarray):
66 raise TypeError("data argument must be a NumPy ndarray")
67 if data.size != 1:
68 raise ValueError("data array must have a size of 1")
69 if data.dtype != expected_dtype:
70 raise ValueError(f"data array must be of dtype {dtype_name}")
71 return lowpp_type.from_ptr(data.ctypes.data, not data.flags.writeable, data)
74# <<<< END OF PREAMBLE CONTENT >>>>
76cimport cython # NOQA
77from libcpp.vector cimport vector
79from cuda.bindings._internal._fast_enum import FastEnum as _FastEnum
82###############################################################################
83# Enum
84###############################################################################
86class Result(_cyb_FastEnum):
87 """
88 The enumerated type `nvrtcResult` defines API call result codes. NVRTC
89 API functions return `nvrtcResult` to indicate the call result.
91 See `nvrtcResult`.
92 """
93 SUCCESS = NVRTC_SUCCESS
94 ERROR_OUT_OF_MEMORY = NVRTC_ERROR_OUT_OF_MEMORY
95 ERROR_PROGRAM_CREATION_FAILURE = NVRTC_ERROR_PROGRAM_CREATION_FAILURE
96 ERROR_INVALID_INPUT = NVRTC_ERROR_INVALID_INPUT
97 ERROR_INVALID_PROGRAM = NVRTC_ERROR_INVALID_PROGRAM
98 ERROR_INVALID_OPTION = NVRTC_ERROR_INVALID_OPTION
99 ERROR_COMPILATION = NVRTC_ERROR_COMPILATION
100 ERROR_BUILTIN_OPERATION_FAILURE = NVRTC_ERROR_BUILTIN_OPERATION_FAILURE
101 ERROR_NO_NAME_EXPRESSIONS_AFTER_COMPILATION = NVRTC_ERROR_NO_NAME_EXPRESSIONS_AFTER_COMPILATION
102 ERROR_NO_LOWERED_NAMES_BEFORE_COMPILATION = NVRTC_ERROR_NO_LOWERED_NAMES_BEFORE_COMPILATION
103 ERROR_NAME_EXPRESSION_NOT_VALID = NVRTC_ERROR_NAME_EXPRESSION_NOT_VALID
104 ERROR_INTERNAL_ERROR = NVRTC_ERROR_INTERNAL_ERROR
105 ERROR_TIME_FILE_WRITE_FAILED = NVRTC_ERROR_TIME_FILE_WRITE_FAILED
106 ERROR_NO_PCH_CREATE_ATTEMPTED = NVRTC_ERROR_NO_PCH_CREATE_ATTEMPTED
107 ERROR_PCH_CREATE_HEAP_EXHAUSTED = NVRTC_ERROR_PCH_CREATE_HEAP_EXHAUSTED
108 ERROR_PCH_CREATE = NVRTC_ERROR_PCH_CREATE
109 ERROR_CANCELLED = NVRTC_ERROR_CANCELLED
110 ERROR_TIME_TRACE_FILE_WRITE_FAILED = NVRTC_ERROR_TIME_TRACE_FILE_WRITE_FAILED
111 ERROR_BUSY = NVRTC_ERROR_BUSY
114class InstallHeadersFlag(_FastEnum):
115 """Flags for :func:`install_bundled_headers`."""
116 SKIP_IF_EXISTS = (
117 0x0,
118 "Skip installation if version marker exists and version matches. "
119 "This is the default behavior when flags=0."
120 )
121 FORCE_OVERWRITE = (
122 0x1,
123 "Clear existing directory contents before installation. "
124 "Guarantees consistency by removing any existing files first."
125 )
126 NO_WAIT = (
127 0x2,
128 "Return NVRTC_ERROR_BUSY immediately if installation is in progress "
129 "by another process, instead of waiting for the lock. "
130 "Can be combined with FORCE_OVERWRITE using bitwise OR. "
131 "Do not wait for installation to complete."
132 )
135###############################################################################
136# Error handling
137###############################################################################
140class NvrtcError(Exception):
141 def __init__(self, status):
142 self.status = status 1E
143 s = get_error_string(status) 1E
144 super(NvrtcError, self).__init__(s) 1E
146 def __reduce__(self):
147 return (type(self), (self.status,))
149class OutOfMemoryError(NvrtcError):
150 pass
151class ProgramCreationFailureError(NvrtcError):
152 pass
153class InvalidInputError(NvrtcError):
154 pass
155class InvalidProgramError(NvrtcError):
156 pass
157class InvalidOptionError(NvrtcError):
158 pass
159class CompilationError(NvrtcError):
160 pass
161class BuiltinOperationFailureError(NvrtcError):
162 pass
163class NoNameExpressionsAfterCompilationError(NvrtcError):
164 pass
165class NoLoweredNamesBeforeCompilationError(NvrtcError):
166 pass
167class NameExpressionNotValidError(NvrtcError):
168 pass
169class InternalError(NvrtcError):
170 pass
171class TimeFileWriteFailedError(NvrtcError):
172 pass
173class NoPchCreateAttemptedError(NvrtcError):
174 pass
175class PchCreateHeapExhaustedError(NvrtcError):
176 pass
177class PchCreateError(NvrtcError):
178 pass
179class CancelledError(NvrtcError):
180 pass
181class TimeTraceFileWriteFailedError(NvrtcError):
182 pass
183class BusyError(NvrtcError):
184 pass
185cdef object _nvrtc_error_factory(int status):
186 cdef object pystatus = status 1E
187 if status == 1: 1E
188 return OutOfMemoryError(pystatus)
189 elif status == 2:
190 return ProgramCreationFailureError(pystatus)
191 elif status == 3:
192 return InvalidInputError(pystatus)
193 elif status == 4:
194 return InvalidProgramError(pystatus) 1E
195 elif status == 5:
196 return InvalidOptionError(pystatus)
197 elif status == 6:
198 return CompilationError(pystatus)
199 elif status == 7:
200 return BuiltinOperationFailureError(pystatus)
201 elif status == 8:
202 return NoNameExpressionsAfterCompilationError(pystatus)
203 elif status == 9:
204 return NoLoweredNamesBeforeCompilationError(pystatus)
205 elif status == 10:
206 return NameExpressionNotValidError(pystatus)
207 elif status == 11:
208 return InternalError(pystatus)
209 elif status == 12:
210 return TimeFileWriteFailedError(pystatus)
211 elif status == 13:
212 return NoPchCreateAttemptedError(pystatus)
213 elif status == 14:
214 return PchCreateHeapExhaustedError(pystatus)
215 elif status == 15:
216 return PchCreateError(pystatus)
217 elif status == 16:
218 return CancelledError(pystatus)
219 elif status == 17:
220 return TimeTraceFileWriteFailedError(pystatus)
221 elif status == 18:
222 return BusyError(pystatus)
223 return NvrtcError(status)
226@cython.profile(False)
227cdef int check_status(int status) except 1 nogil:
228 if status != 0: 1abcdefghijkmnopqrstuvwxyzABCDFElHG
229 with gil: 1E
230 raise _nvrtc_error_factory(status) 1E
231 return status 1abcdefghijkmnopqrstuvwxyzABCDFlHG
234###############################################################################
235# POD definitions
236###############################################################################
238cdef _get_bundled_headers_info_dtype_offsets():
239 cdef nvrtcBundledHeadersInfo *pod = <nvrtcBundledHeadersInfo *>_cyb_calloc(1, sizeof(nvrtcBundledHeadersInfo))
240 if pod == NULL:
241 raise MemoryError("Error allocating nvrtcBundledHeadersInfo")
242 try:
243 return _numpy.dtype({
244 'names': ['available', 'compressed_size', 'uncompressed_size', 'cuda_version_major', 'cuda_version_minor', 'num_files'],
245 'formats': [_numpy.int32, _numpy.uint64, _numpy.uint64, _numpy.int32, _numpy.int32, _numpy.uint32],
246 'offsets': [
247 (<intptr_t>&(pod.available)) - (<intptr_t>pod),
248 (<intptr_t>&(pod.compressedSize)) - (<intptr_t>pod),
249 (<intptr_t>&(pod.uncompressedSize)) - (<intptr_t>pod),
250 (<intptr_t>&(pod.cudaVersionMajor)) - (<intptr_t>pod),
251 (<intptr_t>&(pod.cudaVersionMinor)) - (<intptr_t>pod),
252 (<intptr_t>&(pod.numFiles)) - (<intptr_t>pod),
253 ],
254 'itemsize': sizeof(nvrtcBundledHeadersInfo),
255 })
256 finally:
257 _cyb_free(pod)
259bundled_headers_info_dtype = _get_bundled_headers_info_dtype_offsets()
261cdef class BundledHeadersInfo:
262 """Empty-initialize an instance of `nvrtcBundledHeadersInfo`.
265 .. seealso:: `nvrtcBundledHeadersInfo`
266 """
267 cdef:
268 nvrtcBundledHeadersInfo _data
269 nvrtcBundledHeadersInfo *_ptr
270 object _owner
271 bint _readonly
273 def __init__(self):
274 self._ptr = &self._data 1F
275 self._owner = None 1F
276 self._readonly = False 1F
278 def __repr__(self):
279 return f"<{__name__}.BundledHeadersInfo object at {hex(id(self))}>"
281 @property
282 def ptr(self):
283 """Get the pointer address to the data as Python :class:`int`."""
284 return <intptr_t>(self._ptr)
286 cdef intptr_t _get_ptr(self):
287 return <intptr_t>(self._ptr) 1F
289 def __int__(self):
290 return <intptr_t>(self._ptr)
292 def __eq__(self, other):
293 cdef BundledHeadersInfo other_
294 if not isinstance(other, BundledHeadersInfo):
295 return False
296 other_ = other
297 return (_cyb_memcmp(<void *><intptr_t>(self._ptr), <void *><intptr_t>(other_._ptr), sizeof(nvrtcBundledHeadersInfo)) == 0)
299 def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags):
300 _cyb___getbuffer(self, buffer, <void *>self._ptr, sizeof(nvrtcBundledHeadersInfo), self._readonly)
302 def __releasebuffer__(self, Py_buffer *buffer):
303 pass
305 def __setitem__(self, key, val):
306 cdef _cyb_Py_buffer view
307 if key == 0:
308 if self._readonly:
309 raise ValueError("This BundledHeadersInfo instance is read-only")
310 _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE)
311 try:
312 if <size_t>view.len < sizeof(nvrtcBundledHeadersInfo):
313 raise ValueError(
314 "source buffer too small: expected at least %d bytes, got %d" % (sizeof(nvrtcBundledHeadersInfo), view.len)
315 )
316 _cyb_memmove(<void*>&self._data, view.buf, sizeof(nvrtcBundledHeadersInfo))
317 self._ptr = &self._data
318 self._owner = None
319 self._readonly = view.readonly != 0
320 finally:
321 _cyb_PyBuffer_Release(&view)
322 else:
323 setattr(self, key, val)
325 @property
326 def available(self):
327 """int: Non-zero if bundled headers are available"""
328 return self._ptr[0].available 1F
330 @available.setter
331 def available(self, val):
332 if self._readonly:
333 raise ValueError("This BundledHeadersInfo instance is read-only")
334 self._ptr[0].available = val
336 @property
337 def compressed_size(self):
338 """int: Size of compressed archive in bytes"""
339 return self._ptr[0].compressedSize 1F
341 @compressed_size.setter
342 def compressed_size(self, val):
343 if self._readonly:
344 raise ValueError("This BundledHeadersInfo instance is read-only")
345 self._ptr[0].compressedSize = val
347 @property
348 def uncompressed_size(self):
349 """int: Estimated size when extracted in bytes"""
350 return self._ptr[0].uncompressedSize 1F
352 @uncompressed_size.setter
353 def uncompressed_size(self, val):
354 if self._readonly:
355 raise ValueError("This BundledHeadersInfo instance is read-only")
356 self._ptr[0].uncompressedSize = val
358 @property
359 def cuda_version_major(self):
360 """int: CUDA major version of bundled headers"""
361 return self._ptr[0].cudaVersionMajor 1F
363 @cuda_version_major.setter
364 def cuda_version_major(self, val):
365 if self._readonly:
366 raise ValueError("This BundledHeadersInfo instance is read-only")
367 self._ptr[0].cudaVersionMajor = val
369 @property
370 def cuda_version_minor(self):
371 """int: CUDA minor version of bundled headers"""
372 return self._ptr[0].cudaVersionMinor 1F
374 @cuda_version_minor.setter
375 def cuda_version_minor(self, val):
376 if self._readonly:
377 raise ValueError("This BundledHeadersInfo instance is read-only")
378 self._ptr[0].cudaVersionMinor = val
380 @property
381 def num_files(self):
382 """int: Number of header files in the bundle"""
383 return self._ptr[0].numFiles 1F
385 @num_files.setter
386 def num_files(self, val):
387 if self._readonly:
388 raise ValueError("This BundledHeadersInfo instance is read-only")
389 self._ptr[0].numFiles = val
391 @staticmethod
392 def from_buffer(buffer):
393 """Create an BundledHeadersInfo instance with the memory from the given buffer."""
394 return _cyb_from_buffer(buffer, sizeof(nvrtcBundledHeadersInfo), BundledHeadersInfo)
396 @staticmethod
397 def from_data(data):
398 """Create an BundledHeadersInfo instance wrapping the given NumPy array.
400 Args:
401 data (_numpy.ndarray): a single-element array of dtype `bundled_headers_info_dtype` holding the data.
402 """
403 return _cyb_from_data(data, "bundled_headers_info_dtype", bundled_headers_info_dtype, BundledHeadersInfo)
405 @staticmethod
406 def from_ptr(intptr_t ptr, bint readonly=False, object owner=None):
407 """Create an BundledHeadersInfo instance wrapping the given pointer.
409 Args:
410 ptr (intptr_t): pointer address as Python :class:`int` to the data.
411 owner (object): The Python object that owns the pointer. If not provided, data will be copied.
412 readonly (bool): whether the data is read-only (to the user). default is `False`.
413 """
414 if ptr == 0:
415 raise ValueError("ptr must not be null (0)")
416 cdef BundledHeadersInfo obj = BundledHeadersInfo.__new__(BundledHeadersInfo)
417 if owner is None:
418 _cyb_memcpy(<void*>&obj._data, <void*>ptr, sizeof(nvrtcBundledHeadersInfo))
419 obj._ptr = &obj._data
420 obj._owner = None
421 else:
422 obj._ptr = <nvrtcBundledHeadersInfo *>ptr
423 obj._owner = owner
424 obj._readonly = readonly
425 return obj
428###############################################################################
429# Wrapper functions
430###############################################################################
432cpdef intptr_t create_program(bytes src, name, headers=None, include_names=None) except? 0:
433 """nvrtcCreateProgram creates an instance of nvrtcProgram with the given input parameters.
435 Args:
436 src (bytes): CUDA program source.
437 name (bytes | None): CUDA program name. ``None`` or ``""`` causes ``"default_program"``
438 to be used.
439 headers (list[bytes] | None): Sources of the headers. ``None`` is treated as an empty
440 list (no headers).
441 include_names (list[bytes] | None): Name of each header by which it can be included in
442 the CUDA program source. Must have the same length as *headers*.
444 Returns:
445 intptr_t: Opaque handle to the created program. Pass to :func:`destroy_program` when done.
447 .. seealso:: `nvrtcCreateProgram`
448 """
449 if headers is None: 1bcdefghijkmnopqrstuvwxyzABCDl
450 headers = [] 1bcdefghijkmnopqrstuvwxyzABCD
451 if include_names is None: 1bcdefghijkmnopqrstuvwxyzABCDl
452 include_names = [] 1bcdefghijkmnopqrstuvwxyzABCD
453 if len(headers) != len(include_names): 1bcdefghijkmnopqrstuvwxyzABCDl
454 raise ValueError(
455 f"headers and include_names must have the same length "
456 f"({len(headers)} != {len(include_names)})"
457 )
458 cdef int num_headers = len(headers) 1bcdefghijkmnopqrstuvwxyzABCDl
459 cdef Program prog
460 cdef const char* c_src = src 1bcdefghijkmnopqrstuvwxyzABCDl
461 cdef bytes _name
462 if name is None: 1bcdefghijkmnopqrstuvwxyzABCDl
463 _name = b""
464 else:
465 _name = name 1bcdefghijkmnopqrstuvwxyzABCDl
466 cdef const char* c_name = _name 1bcdefghijkmnopqrstuvwxyzABCDl
467 cdef vector[const char*] cy_headers = headers 1bcdefghijkmnopqrstuvwxyzABCDl
468 cdef vector[const char*] cy_include_names = include_names 1bcdefghijkmnopqrstuvwxyzABCDl
469 cdef const char** hdr_data = NULL 1bcdefghijkmnopqrstuvwxyzABCDl
470 cdef const char** inc_data = NULL 1bcdefghijkmnopqrstuvwxyzABCDl
471 if num_headers: 1bcdefghijkmnopqrstuvwxyzABCDl
472 hdr_data = cy_headers.data()
473 inc_data = cy_include_names.data()
474 with nogil: 1bcdefghijkmnopqrstuvwxyzABCDl
475 __status__ = nvrtcCreateProgram(&prog, c_src, c_name, num_headers, hdr_data, inc_data) 1bcdefghijkmnopqrstuvwxyzABCDl
476 check_status(__status__) 1bcdefghijkmnopqrstuvwxyzABCDl
477 return <intptr_t>prog 1bcdefghijkmnopqrstuvwxyzABCDl
480cpdef compile_program(intptr_t prog, options=None):
481 """nvrtcCompileProgram compiles the given program.
483 It supports compile options listed in Supported Compile Options.
485 Args:
486 prog (intptr_t): CUDA Runtime Compilation program.
487 options (list[bytes] | None): Compiler options as a list of byte strings.
488 May be ``None`` or an empty list for no options.
490 .. seealso:: `nvrtcCompileProgram`
491 """
492 if options is None: 1bcdefghijkmnopqrstuvwxyzABCDl
493 options = []
494 cdef int num_options = len(options) 1bcdefghijkmnopqrstuvwxyzABCDl
495 cdef vector[const char*] cy_options = options 1bcdefghijkmnopqrstuvwxyzABCDl
496 cdef const char** opt_data = NULL 1bcdefghijkmnopqrstuvwxyzABCDl
497 if num_options: 1bcdefghijkmnopqrstuvwxyzABCDl
498 opt_data = cy_options.data() 1bcdefghijkmnopqrstuvwxyzABCD
499 with nogil: 1bcdefghijkmnopqrstuvwxyzABCDl
500 __status__ = nvrtcCompileProgram(<Program>prog, num_options, opt_data) 1bcdefghijkmnopqrstuvwxyzABCDl
501 check_status(__status__) 1bcdefghijkmnopqrstuvwxyzABCDl
504cpdef set_flow_callback(intptr_t prog, intptr_t callback, intptr_t payload):
505 """nvrtcSetFlowCallback registers a callback that the compiler invokes during :func:`compile_program`.
507 The callback signature must be ``int callback(void *param1, void *param2)``.
508 The compiler passes *payload* as *param1* and ``NULL`` as *param2* (reserved).
509 Return 1 to cancel compilation, 0 to continue; the callback must return
510 consistently, be thread-safe, and must not call any NVRTC/libnvvm/PTX APIs.
512 Pass *callback* as a raw C function-pointer integer (e.g. via ``ctypes.cast``).
513 Pass 0 for *callback* to clear a previously registered callback.
515 Args:
516 prog (intptr_t): CUDA Runtime Compilation program.
517 callback (intptr_t): C function pointer ``int (*)(void*, void*)`` cast to an integer,
518 or 0 to clear.
519 payload (intptr_t): Opaque pointer passed to the callback as its first argument.
521 .. seealso:: `nvrtcSetFlowCallback`
522 """
523 with nogil:
524 __status__ = nvrtcSetFlowCallback(<Program>prog, <void*>callback, <void*>payload)
525 check_status(__status__)
528cpdef str get_error_string(int result):
529 """nvrtcGetErrorString is a helper function that returns a string describing the given ``nvrtcResult`` code, e.g., NVRTC_SUCCESS to ``"NVRTC_SUCCESS"``. For unrecognized enumeration values, it returns ``"NVRTC_ERROR unknown"``.
532 Args:
533 result (Result): CUDA Runtime Compilation API result code.
535 .. seealso:: `nvrtcGetErrorString`
536 """
537 cdef const char *_output_cstr_
538 cdef bytes _output_
539 with nogil: 1E
540 _output_cstr_ = nvrtcGetErrorString(<nvrtcResult>result) 1E
541 _output_ = _output_cstr_ 1E
542 return _output_.decode() 1E
545cpdef tuple version():
546 """nvrtcVersion sets the output parameters ``major`` and ``minor`` with the CUDA Runtime Compilation version number.
549 Returns:
550 A 2-tuple containing:
551 - int: CUDA Runtime Compilation major version number.
552 - int: CUDA Runtime Compilation minor version number.
554 .. seealso:: `nvrtcVersion`
555 """
556 cdef int major
557 cdef int minor
558 with nogil: 1abcdefghijk
559 __status__ = nvrtcVersion(&major, &minor) 1abcdefghijk
560 check_status(__status__) 1abcdefghijk
561 return (major, minor) 1abcdefghijk
564cpdef int get_num_supported_archs() except? -1:
565 """nvrtcGetNumSupportedArchs sets the output parameter ``num_archs`` with the number of architectures supported by NVRTC. This can then be used to pass an array to ``nvrtcGetSupportedArchs`` to get the supported architectures.
567 see ``nvrtcGetSupportedArchs``.
569 Returns:
570 int: number of supported architectures.
572 .. seealso:: `nvrtcGetNumSupportedArchs`
573 """
574 cdef int num_archs
575 with nogil:
576 __status__ = nvrtcGetNumSupportedArchs(&num_archs)
577 check_status(__status__)
578 return num_archs
581cpdef object get_supported_archs():
582 """nvrtcGetSupportedArchs populates the array passed via the output parameter ``supported_archs`` with the architectures supported by NVRTC. The array is sorted in the ascending order. The size of the array to be passed can be determined using ``nvrtcGetNumSupportedArchs``.
584 see ``nvrtcGetNumSupportedArchs``.
586 Returns:
587 int: sorted array of supported architectures.
589 .. seealso:: `nvrtcGetSupportedArchs`
590 """
591 cdef int numArchs
592 with nogil: 1H
593 __status__ = nvrtcGetNumSupportedArchs(&numArchs) 1H
594 check_status(__status__) 1H
595 cdef _cyb_view.array _supported_archs_alloc_ = _cyb_view.array(shape=(max(numArchs, 1),), itemsize=sizeof(int), format="i", mode="c") 1H
596 cdef int *supported_archs_ptr = <int *>(_supported_archs_alloc_.data) 1H
597 cdef object supported_archs = _supported_archs_alloc_[:numArchs] 1H
598 if numArchs != 0: 1H
599 with nogil: 1H
600 __status__ = nvrtcGetSupportedArchs(supported_archs_ptr) 1H
601 check_status(__status__) 1H
602 return supported_archs 1H
605cpdef destroy_program(intptr_t prog):
606 """nvrtcDestroyProgram destroys the given program.
609 Args:
610 prog (intptr_t): CUDA Runtime Compilation program.
612 .. seealso:: `nvrtcDestroyProgram`
613 """
614 cdef nvrtcProgram _prog_ = <nvrtcProgram>prog 1l
615 with nogil: 1l
616 __status__ = nvrtcDestroyProgram(&_prog_) 1l
617 check_status(__status__) 1l
620cpdef size_t get_ptx_size(intptr_t prog) except? 0:
621 """nvrtcGetPTXSize sets the value of ``ptx_size_ret`` with the size of the PTX generated by the previous compilation of ``prog`` (including the trailing ``NULL``).
624 Args:
625 prog (intptr_t): CUDA Runtime Compilation program.
627 Returns:
628 size_t: Size of the generated PTX (including the trailing
629 ``NULL``).
631 .. seealso:: `nvrtcGetPTXSize`
632 """
633 cdef size_t ptx_size_ret
634 with nogil:
635 __status__ = nvrtcGetPTXSize(<nvrtcProgram>prog, &ptx_size_ret)
636 check_status(__status__)
637 return ptx_size_ret
640cpdef bytes get_ptx(intptr_t prog):
641 """nvrtcGetPTX stores the PTX generated by the previous compilation of ``prog`` in the memory pointed by ``ptx``.
644 Args:
645 prog (intptr_t): CUDA Runtime Compilation program.
647 Returns:
648 bytes: Compiled result.
650 .. seealso:: `nvrtcGetPTX`
651 """
652 cdef size_t ptxSizeRet
653 with nogil:
654 __status__ = nvrtcGetPTXSize(<nvrtcProgram>prog, &ptxSizeRet)
655 check_status(__status__)
656 cdef bytes _ptx_ = bytes(ptxSizeRet)
657 cdef char* ptx = _ptx_
658 if ptxSizeRet != 0:
659 with nogil:
660 __status__ = nvrtcGetPTX(<nvrtcProgram>prog, ptx)
661 check_status(__status__)
662 return _ptx_
665cpdef size_t get_cubin_size(intptr_t prog) except? 0:
666 """nvrtcGetCUBINSize sets the value of ``cubin_size_ret`` with the size of the cubin generated by the previous compilation of ``prog``. The value of cubin_size_ret is set to 0 if the value specified to ``-arch`` is a virtual architecture instead of an actual architecture.
669 Args:
670 prog (intptr_t): CUDA Runtime Compilation program.
672 Returns:
673 size_t: Size of the generated cubin.
675 .. seealso:: `nvrtcGetCUBINSize`
676 """
677 cdef size_t cubin_size_ret
678 with nogil:
679 __status__ = nvrtcGetCUBINSize(<nvrtcProgram>prog, &cubin_size_ret)
680 check_status(__status__)
681 return cubin_size_ret
684cpdef bytes get_cubin(intptr_t prog):
685 """nvrtcGetCUBIN stores the cubin generated by the previous compilation of ``prog`` in the memory pointed by ``cubin``. No cubin is available if the value specified to ``-arch`` is a virtual architecture instead of an actual architecture. The cubin does not contain code for the Tile functions (``__tile__`` / ``__tile_global__``) or variables (``__tile__``); use :func:`get_tile_ir` to extract the cuda_tile IR generated for Tile code.
688 Args:
689 prog (intptr_t): CUDA Runtime Compilation program.
691 Returns:
692 bytes: Compiled and assembled result.
694 .. seealso:: `nvrtcGetCUBIN`
695 """
696 cdef size_t cubinSizeRet
697 with nogil: 1bcdefghijkqrstuv
698 __status__ = nvrtcGetCUBINSize(<nvrtcProgram>prog, &cubinSizeRet) 1bcdefghijkqrstuv
699 check_status(__status__) 1bcdefghijkqrstuv
700 cdef bytes _cubin_ = bytes(cubinSizeRet) 1bcdefghijkqrstuv
701 cdef char* cubin = _cubin_ 1bcdefghijkqrstuv
702 if cubinSizeRet != 0: 1bcdefghijkqrstuv
703 with nogil: 1bcdefghijkqrstuv
704 __status__ = nvrtcGetCUBIN(<nvrtcProgram>prog, cubin) 1bcdefghijkqrstuv
705 check_status(__status__) 1bcdefghijkqrstuv
706 return _cubin_ 1bcdefghijkqrstuv
709cpdef size_t get_ltoir_size(intptr_t prog) except? 0:
710 """nvrtcGetLTOIRSize sets the value of ``ltoir_size_ret`` with the size of the LTO IR generated by the previous compilation of ``prog``. The value of ltoir_size_ret is set to 0 if the program was not compiled with ``-dlto``.
713 Args:
714 prog (intptr_t): CUDA Runtime Compilation program.
716 Returns:
717 size_t: Size of the generated LTO IR.
719 .. seealso:: `nvrtcGetLTOIRSize`
720 """
721 cdef size_t ltoir_size_ret
722 with nogil:
723 __status__ = nvrtcGetLTOIRSize(<nvrtcProgram>prog, <oir_size_ret)
724 check_status(__status__)
725 return ltoir_size_ret
728cpdef bytes get_ltoir(intptr_t prog):
729 """nvrtcGetltoir stores the LTO IR generated by the previous compilation of ``prog`` in the memory pointed by ``ltoir``. No LTO IR is available if the program was compiled without ``-dlto``.
732 Args:
733 prog (intptr_t): CUDA Runtime Compilation program.
735 Returns:
736 bytes: Compiled result.
738 .. seealso:: `nvrtcGetLTOIR`
739 """
740 cdef size_t LTOIRSizeRet
741 with nogil: 1mnopwxyzABCD
742 __status__ = nvrtcGetLTOIRSize(<nvrtcProgram>prog, <OIRSizeRet) 1mnopwxyzABCD
743 check_status(__status__) 1mnopwxyzABCD
744 cdef bytes _ltoir_ = bytes(LTOIRSizeRet) 1mnopwxyzABCD
745 cdef char* ltoir = _ltoir_ 1mnopwxyzABCD
746 if LTOIRSizeRet != 0: 1mnopwxyzABCD
747 with nogil: 1mnopwxyzABCD
748 __status__ = nvrtcGetLTOIR(<nvrtcProgram>prog, ltoir) 1mnopwxyzABCD
749 check_status(__status__) 1mnopwxyzABCD
750 return _ltoir_ 1mnopwxyzABCD
753cpdef size_t get_optix_ir_size(intptr_t prog) except? 0:
754 """nvrtcGetOptiXIRSize sets the value of ``optixir_size_ret`` with the size of the OptiX IR generated by the previous compilation of ``prog``. The value of nvrtcGetOptiXIRSize is set to 0 if the program was compiled with options incompatible with OptiX IR generation.
757 Args:
758 prog (intptr_t): CUDA Runtime Compilation program.
760 Returns:
761 size_t: Size of the generated LTO IR.
763 .. seealso:: `nvrtcGetOptiXIRSize`
764 """
765 cdef size_t optixir_size_ret
766 with nogil:
767 __status__ = nvrtcGetOptiXIRSize(<nvrtcProgram>prog, &optixir_size_ret)
768 check_status(__status__)
769 return optixir_size_ret
772cpdef bytes get_optix_ir(intptr_t prog):
773 """nvrtcGetOptiXIR stores the OptiX IR generated by the previous compilation of ``prog`` in the memory pointed by ``optixir``. No OptiX IR is available if the program was compiled with options incompatible with OptiX IR generation.
776 Args:
777 prog (intptr_t): CUDA Runtime Compilation program.
779 Returns:
780 bytes: Optix IR Compiled result.
782 .. seealso:: `nvrtcGetOptiXIR`
783 """
784 cdef size_t optixirSizeRet
785 with nogil:
786 __status__ = nvrtcGetOptiXIRSize(<nvrtcProgram>prog, &optixirSizeRet)
787 check_status(__status__)
788 cdef bytes _optixir_ = bytes(optixirSizeRet)
789 cdef char* optixir = _optixir_
790 if optixirSizeRet != 0:
791 with nogil:
792 __status__ = nvrtcGetOptiXIR(<nvrtcProgram>prog, optixir)
793 check_status(__status__)
794 return _optixir_
797cpdef size_t get_program_log_size(intptr_t prog) except? 0:
798 """nvrtcGetProgramLogSize sets ``log_size_ret`` with the size of the log generated by the previous compilation of ``prog`` (including the trailing ``NULL``).
800 Note that compilation log may be generated with warnings and informative
801 messages, even when the compilation of ``prog`` succeeds.
803 Args:
804 prog (intptr_t): CUDA Runtime Compilation program.
806 Returns:
807 size_t: Size of the compilation log (including the trailing
808 ``NULL``).
810 .. seealso:: `nvrtcGetProgramLogSize`
811 """
812 cdef size_t log_size_ret
813 with nogil:
814 __status__ = nvrtcGetProgramLogSize(<nvrtcProgram>prog, &log_size_ret)
815 check_status(__status__)
816 return log_size_ret
819cpdef bytes get_program_log(intptr_t prog):
820 """nvrtcGetProgramLog stores the log generated by the previous compilation of ``prog`` in the memory pointed by ``log``.
823 Args:
824 prog (intptr_t): CUDA Runtime Compilation program.
826 Returns:
827 bytes: Compilation log.
829 .. seealso:: `nvrtcGetProgramLog`
830 """
831 cdef size_t logSizeRet
832 with nogil: 1bcdefghijk
833 __status__ = nvrtcGetProgramLogSize(<nvrtcProgram>prog, &logSizeRet) 1bcdefghijk
834 check_status(__status__) 1bcdefghijk
835 cdef bytes _log_ = bytes(logSizeRet) 1bcdefghijk
836 cdef char* log = _log_ 1bcdefghijk
837 if logSizeRet != 0: 1bcdefghijk
838 with nogil: 1bcdefghijk
839 __status__ = nvrtcGetProgramLog(<nvrtcProgram>prog, log) 1bcdefghijk
840 check_status(__status__) 1bcdefghijk
841 return _log_ 1bcdefghijk
844cpdef add_name_expression(intptr_t prog, name_expression):
845 """nvrtcAddNameExpression notes the given name expression denoting the address of a global function or device/__constant__ variable.
847 The identical name expression string must be provided on a subsequent call to
848 nvrtcGetLoweredName to extract the lowered name.
850 Args:
851 prog (intptr_t): CUDA Runtime Compilation program.
852 name_expression (str): constant expression denoting the address of
853 a global function or device/__constant__ variable.
855 .. seealso:: `nvrtcAddNameExpression`
856 """
857 if not isinstance(name_expression, str): 1l
858 raise TypeError("name_expression must be a Python str")
859 cdef bytes _temp_name_expression_ = (<str>name_expression).encode() 1l
860 cdef char* _name_expression_ = _temp_name_expression_ 1l
861 with nogil: 1l
862 __status__ = nvrtcAddNameExpression(<nvrtcProgram>prog, <const char*>_name_expression_) 1l
863 check_status(__status__) 1l
866cpdef bytes get_lowered_name(intptr_t prog, name_expression):
867 """nvrtcGetLoweredName extracts the lowered (mangled) name for a global function or device/__constant__ variable, and updates \*lowered_name to point to it. The memory containing the name is released when the NVRTC program is destroyed by nvrtcDestroyProgram. The identical name expression must have been previously provided to nvrtcAddNameExpression.
870 Args:
871 prog (intptr_t): CUDA Runtime Compilation program.
872 name_expression (str): constant expression denoting the address of
873 a global function or device/__constant__ variable.
875 Returns:
876 bytes: initialized by the function to point to a C string
877 containing the lowered (mangled) name corresponding to the
878 provided name expression.
880 .. seealso:: `nvrtcGetLoweredName`
881 """
882 if not isinstance(name_expression, str): 1El
883 raise TypeError("name_expression must be a Python str")
884 cdef bytes _temp_name_expression_ = (<str>name_expression).encode() 1El
885 cdef char* _name_expression_ = _temp_name_expression_ 1El
886 cdef const char* lowered_name = NULL 1El
887 with nogil: 1El
888 __status__ = nvrtcGetLoweredName(<nvrtcProgram>prog, <const char*>_name_expression_, &lowered_name) 1El
889 check_status(__status__) 1El
890 return (<bytes>lowered_name) if lowered_name != NULL else b"" 1l
893cpdef size_t get_pch_heap_size() except? 0:
894 """retrieve the current size of the PCH Heap.
897 Returns:
898 size_t: pointer to location where the size of the PCH Heap will be
899 stored.
901 .. seealso:: `nvrtcGetPCHHeapSize`
902 """
903 cdef size_t ret
904 with nogil:
905 __status__ = nvrtcGetPCHHeapSize(&ret)
906 check_status(__status__)
907 return ret
910cpdef set_pch_heap_size(size_t size):
911 """set the size of the PCH Heap.
913 The requested size may be rounded up to a platform dependent alignment (e.g.
914 page size). If the PCH Heap has already been allocated, the heap memory will be
915 freed and a new PCH Heap will be allocated.
917 Args:
918 size (size_t): requested size of the PCH Heap, in bytes.
920 .. seealso:: `nvrtcSetPCHHeapSize`
921 """
922 with nogil:
923 __status__ = nvrtcSetPCHHeapSize(size)
924 check_status(__status__)
927cpdef int get_pch_create_status(intptr_t prog) except? -1:
928 """returns the PCH creation status.
930 NVRTC_SUCCESS indicates that the PCH was successfully created.
931 NVRTC_ERROR_NO_PCH_CREATE_ATTEMPTED indicates that no PCH creation was
932 attempted, either because PCH functionality was not requested during the
933 preceding nvrtcCompileProgram call, or automatic PCH processing was requested,
934 and compiler chose not to create a PCH file.
935 NVRTC_ERROR_PCH_CREATE_HEAP_EXHAUSTED indicates that a PCH file could
936 potentially have been created, but the compiler ran out space in the PCH heap.
937 In this scenario, the :func:`get_pch_heap_size_required` can be used to query
938 the required heap size, the heap can be reallocated for this size with
939 :func:`set_pch_heap_size` and PCH creation may be reattempted again invoking
940 :func:`compile_program` with a new NVRTC program instance.
941 NVRTC_ERROR_PCH_CREATE indicates that an error condition prevented the PCH file
942 from being created.
944 Args:
945 prog (intptr_t): CUDA Runtime Compilation program.
947 .. seealso:: `nvrtcGetPCHCreateStatus`
948 """
949 cdef int ret
950 with nogil:
951 ret = <int>nvrtcGetPCHCreateStatus(<nvrtcProgram>prog)
952 return ret
955cpdef size_t get_pch_heap_size_required(intptr_t prog) except? 0:
956 """retrieve the required size of the PCH heap required to compile the given program.
959 Args:
960 prog (intptr_t): CUDA Runtime Compilation program.
962 Returns:
963 size_t: pointer to location where the required size of the PCH
964 Heap will be stored.
966 .. seealso:: `nvrtcGetPCHHeapSizeRequired`
967 """
968 cdef size_t size
969 with nogil:
970 __status__ = nvrtcGetPCHHeapSizeRequired(<nvrtcProgram>prog, &size)
971 check_status(__status__)
972 return size
975cpdef size_t get_tile_ir_size(intptr_t prog) except? 0:
976 """nvrtcGetTileIRSize sets the value of ``tile_ir_size_ret`` with the size of the cuda_tile IR generated by the previous compilation of ``prog``.
979 Args:
980 prog (intptr_t): CUDA Runtime Compilation program.
982 Returns:
983 size_t: Size of the generated cuda_tile IR.
985 .. seealso:: `nvrtcGetTileIRSize`
986 """
987 cdef size_t tile_ir_size_ret
988 with nogil:
989 __status__ = nvrtcGetTileIRSize(<nvrtcProgram>prog, &tile_ir_size_ret)
990 check_status(__status__)
991 return tile_ir_size_ret
994cpdef bytes get_tile_ir(intptr_t prog):
995 """nvrtcGettile_ir stores the cuda_tile IR generated by the previous compilation of ``prog`` in the memory pointed by ``tile_ir``.
998 Args:
999 prog (intptr_t): CUDA Runtime Compilation program.
1001 Returns:
1002 bytes: Generated cuda_tile IR.
1004 .. seealso:: `nvrtcGetTileIR`
1005 """
1006 cdef size_t TileIRSizeRet
1007 with nogil:
1008 __status__ = nvrtcGetTileIRSize(<nvrtcProgram>prog, &TileIRSizeRet)
1009 check_status(__status__)
1010 cdef bytes _tile_ir_ = bytes(TileIRSizeRet)
1011 cdef char* tile_ir = _tile_ir_
1012 if TileIRSizeRet != 0:
1013 with nogil:
1014 __status__ = nvrtcGetTileIR(<nvrtcProgram>prog, tile_ir)
1015 check_status(__status__)
1016 return _tile_ir_
1019cpdef bytes install_bundled_headers(install_path, unsigned int flags):
1020 """nvrtcInstallBundledHeaders extracts CUDA headers bundled with NVRTC to a specified directory for use during compilation.
1022 NVRTC bundles a set of CUDA Toolkit headers and CUDA C++ Core Libraries (CCCL)
1023 within libnvrtc-builtins. This function extracts these headers to the specified
1024 directory, allowing NVRTC programs to compile without requiring a separate CUDA
1025 Toolkit installation. The bundled headers match those available in the CUDA
1026 Toolkit plus CCCL libraries.
1027 After extraction, users can compile kernels by passing appropriate include
1028 paths (such as "-I<install_path>" and "-I<install_path>/cccl") to
1029 nvrtcCompileProgram.
1030 A version marker file (.nvrtc_headers_version) is created in the installation
1031 directory to track the installed version.
1032 This function is thread-safe and process-safe. Concurrent calls from multiple
1033 threads or processes will be serialized using file locking. By default, the
1034 function waits for the lock; use NVRTC_INSTALL_HEADERS_NO_WAIT to return
1035 immediately with NVRTC_ERROR_BUSY if another process holds the lock.
1037 Args:
1038 install_path (str): Path where headers should be extracted (UTF-8
1039 encoded). The directory will be created if it doesn't exist.
1040 flags (unsigned int): NVRTC_INSTALL_HEADERS_* flags:.
1042 Returns:
1043 bytes: Optional pointer to receive detailed error message on
1044 failure. If non-NULL, ``*error_log`` will be set to point to a
1045 string describing the error cause. Note: subsequent API calls
1046 from the same thread may overwrite this message. May be NULL
1047 if error details are not needed.
1049 .. note::
1050 Use NVRTC_INSTALL_HEADERS_SKIP_IF_EXISTS to avoid reinstalling if headers
1051 already exist. Use NVRTC_INSTALL_HEADERS_FORCE_OVERWRITE to guarantee
1052 consistency by clearing the directory first.
1053 .. seealso:: `nvrtcInstallBundledHeaders`
1054 """
1055 if not isinstance(install_path, str): 1G
1056 raise TypeError("install_path must be a Python str")
1057 cdef bytes _temp_install_path_ = (<str>install_path).encode() 1G
1058 cdef char* _install_path_ = _temp_install_path_ 1G
1059 cdef const char* error_log = NULL 1G
1060 with nogil: 1G
1061 __status__ = nvrtcInstallBundledHeaders(<const char*>_install_path_, flags, &error_log) 1G
1062 check_status(__status__) 1G
1063 return (<bytes>error_log) if error_log != NULL else b"" 1G
1066cpdef tuple get_bundled_headers_info():
1067 """nvrtcGetBundledHeadersInfo queries information about the bundled headers without extracting them.
1069 This function allows users to determine if bundled headers are available and
1070 get size estimates before calling nvrtcInstallBundledHeaders.
1072 Returns:
1073 A 2-tuple containing:
1074 - nvrtcBundledHeadersInfo: Pointer to structure to receive header
1075 information.
1076 - bytes: Optional pointer to receive detailed error message on
1077 failure. If non-NULL, ``*error_log`` will be set to point to a
1078 string describing the error cause. Note: subsequent API calls
1079 from the same thread may overwrite this message. May be NULL
1080 if error details are not needed.
1082 .. seealso:: `nvrtcGetBundledHeadersInfo`
1083 """
1084 cdef BundledHeadersInfo info_py = BundledHeadersInfo() 1F
1085 cdef nvrtcBundledHeadersInfo *info = <nvrtcBundledHeadersInfo *><intptr_t>(info_py._get_ptr()) 1F
1086 cdef const char* error_log = NULL 1F
1087 with nogil: 1F
1088 __status__ = nvrtcGetBundledHeadersInfo(info, &error_log) 1F
1089 check_status(__status__) 1F
1090 return (info_py, (<bytes>error_log) if error_log != NULL else b"") 1F
1093cpdef bytes remove_bundled_headers(install_path):
1094 """nvrtcRemoveBundledHeaders removes previously installed bundled headers.
1096 This function removes the headers installed by nvrtcInstallBundledHeaders,
1097 helping users manage disk space. It recursively removes all files and
1098 subdirectories within the installation directory.
1100 Args:
1101 install_path (str): Path where headers were previously installed.
1102 Must be the same path used with nvrtcInstallBundledHeaders.
1104 Returns:
1105 bytes: Optional pointer to receive detailed error message on
1106 failure. If non-NULL, ``*error_log`` will be set to point to a
1107 string describing the error cause. Note: subsequent API calls
1108 from the same thread may overwrite this message. May be NULL
1109 if error details are not needed.
1111 .. note::
1112 This function will remove ALL contents of the specified directory, not just
1113 files installed by NVRTC. Use with caution.
1114 .. seealso:: `nvrtcRemoveBundledHeaders`
1115 """
1116 if not isinstance(install_path, str): 1G
1117 raise TypeError("install_path must be a Python str")
1118 cdef bytes _temp_install_path_ = (<str>install_path).encode() 1G
1119 cdef char* _install_path_ = _temp_install_path_ 1G
1120 cdef const char* error_log = NULL 1G
1121 with nogil: 1G
1122 __status__ = nvrtcRemoveBundledHeaders(<const char*>_install_path_, &error_log) 1G
1123 check_status(__status__) 1G
1124 return (<bytes>error_log) if error_log != NULL else b"" 1G
1125del _cyb_FastEnum