Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions cuda_core/cuda/core/_utils/cuda_utils.pxd
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,14 @@ ctypedef fused integer_t:
cdef const cydriver.CUcontext CU_CONTEXT_INVALID = <cydriver.CUcontext>(-2)


# Number of threads registered through cuda.core.utils.register. While it is 0,
# a driver call adds only this one load to its success path.
cdef int _driver_log_users


cdef inline int HANDLE_RETURN(cydriver.CUresult err) except?-1 nogil:
if _driver_log_users:
return _driver_log_after_call(err)
if err != cydriver.CUresult.CUDA_SUCCESS:
return _check_driver_error(err)
return 0
Expand Down Expand Up @@ -61,12 +68,15 @@ cdef object _NVRTC_SUCCESS
# Out-of-line failure paths for the inline checks below; keeps the error
# formatting (and its Python-level dependencies) out of every cimporting module.
cdef int _raise_driver_error(cydriver.CUresult error) except -1 nogil
cdef int _driver_log_after_call(cydriver.CUresult error) except?-1 nogil
cdef int _raise_runtime_error(error) except -1
cdef int _raise_nvrtc_status_error(error, handle) except -1


# TODO: stop exposing these within the codebase?
cpdef inline int _check_driver_error(cydriver.CUresult error) except?-1 nogil:
if _driver_log_users:
return _driver_log_after_call(error)
if error == cydriver.CUresult.CUDA_SUCCESS:
return 0
return _raise_driver_error(error)
Expand Down
48 changes: 47 additions & 1 deletion cuda_core/cuda/core/_utils/cuda_utils.pyi
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
# This file was generated by stubgen-pyx v0.2.23 from cuda_core/cuda/core/_utils/cuda_utils.pyx

from typing import Any, Callable, NamedTuple
import logging
import threading
from typing import Any, Callable, NamedTuple, TypedDict

from cuda.bindings import cydriver
from cuda.bindings import driver as driver
from cuda.bindings import nvrtc as nvrtc
from cuda.bindings import runtime as runtime
Expand All @@ -11,8 +14,16 @@ _keep_nvrtc_in_stub: nvrtc.nvrtcResult
_keep_runtime_in_stub: runtime.cudaError_t
_RUNTIME_SUCCESS = runtime.cudaError_t.cudaSuccess
_NVRTC_SUCCESS = nvrtc.nvrtcResult.NVRTC_SUCCESS
_driver_log_users = 0
_driver_log_users_lock = threading.Lock()
_driver_log_settings = threading.local()
_fork_warning_checked = False

class CudaCoreDriverLog(TypedDict):
mode: int
it: cydriver.CUlogIterator
tid: int

class CUDAError(Exception):
"""Raised when a CUDA driver or runtime call fails.

Expand Down Expand Up @@ -64,6 +75,41 @@ class ComputeCapability(NamedTuple):
minor: int

def cast_to_3_tuple(label: str, cfg: int | tuple[int, ...]) -> tuple[int, int, int]: ...
def _parse_driver_log(lines: bytes) -> list[tuple[str, str]]:
"""Split "[time][tid][lib][E/W] message" lines into (level, message) pairs."""
def _log_driver_messages(lines: bytes) -> None: ...
def register(logger: logging.Logger | None=None, *, cuda_error_as: int=40, cuda_warn_as: int=30) -> None:
"""Report the CUDA driver's log messages for the calling thread's cuda.core calls.

With a ``logger``, the messages that the driver logs for the calling
thread are passed to ``logger`` after each cuda.core driver call. With
``None``, they are instead attached as notes (``__notes__``) to the
:class:`~cuda.core.CUDAError` that a failing cuda.core driver call raises.
Messages logged before this call are excluded. Calling it again on a
registered thread has no effect.

Parameters
----------
logger : logging.Logger, optional
The logger that receives the messages, or ``None`` for exception notes.
cuda_error_as : int, optional
The logging level of the driver's error messages. Default:
``logging.ERROR``.
cuda_warn_as : int, optional
The logging level of the driver's warning messages. Default:
``logging.WARNING``.

Raises
------
RuntimeError
If the CUDA driver is older than 12.9, which has no log.
"""
def unregister() -> None:
"""Stop reporting the driver's log messages for the calling thread.

Undoes :func:`register`. Calling it on a thread that is not registered has
no effect.
"""
def handle_return(result: tuple[Any, ...], handle: object | None=None) -> Any: ...
def check_or_create_options(cls: type, options: object, options_description: str='', keep_none: bool=False) -> object:
"""
Expand Down
197 changes: 197 additions & 0 deletions cuda_core/cuda/core/_utils/cuda_utils.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@
# SPDX-License-Identifier: Apache-2.0

import functools
import logging
import multiprocessing
import platform
import threading
import warnings
from collections.abc import Sequence
from typing import Any, Callable, NamedTuple
Expand Down Expand Up @@ -184,9 +186,200 @@ cdef inline void _attach_detail(exc, str detail):
exc.add_note(detail)


# Driver log messages (cuda.core.utils.register). The state is a C++
# thread_local defined only in this module, so each thread has one instance
# shared by every cuda.core module.
cdef extern from *:
"""
#include <cstdlib>
#include <cstring>
#include <cuda.h>
#ifdef _WIN32
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
static long cuda_core_thread_id(int kernel) { (void)kernel; return (long)GetCurrentThreadId(); }
#else
#include <pthread.h>
#include <sys/syscall.h>
#include <unistd.h>
// The driver prints the kernel thread id (kernel=1) or the pthread id.
static long cuda_core_thread_id(int kernel) {
return kernel ? (long)syscall(SYS_gettid) : (long)pthread_self();
}
#endif

struct CudaCoreDriverLog { int mode; CUlogIterator it; long tid; };
static thread_local CudaCoreDriverLog cuda_core_driver_log = {0, 0, 0};

// Keeps, in place, the lines of buf whose "[time][tid][lib][E/W] " prefix
// carries tid, and returns their total length.
static size_t cuda_core_keep_thread_lines(char *buf, size_t n, long tid) {
size_t out = 0;
for (size_t i = 0; i < n;) {
const char *line = buf + i;
const char *nl = (const char *)memchr(line, '\\n', n - i);
size_t len = nl ? (size_t)(nl - line) + 1 : n - i;
const char *p = line[0] == '[' ? (const char *)memchr(line, ']', len) : NULL;
if (p && p[1] == '[') {
char *end;
long t = strtol(p + 2, &end, 10);
if (end != p + 2 && *end == ']' && t == tid) {
memmove(buf + out, line, len);
out += len;
}
}
i += len;
}
return out;
}
"""
ctypedef struct CudaCoreDriverLog:
int mode
cydriver.CUlogIterator it
long tid
CudaCoreDriverLog cuda_core_driver_log
long cuda_core_thread_id(int kernel) nogil
size_t cuda_core_keep_thread_lines(char* buf, size_t n, long tid) nogil


cdef enum:
_LOG_TO_LOGGER = 1 # register(logger): Sections 2 and 3 of the design
_LOG_TO_NOTES = 2 # register(None): Section 4 of the design
_LOG_DUMP_SIZE = 25600 # cuLogsDumpToMemory overruns smaller buffers (NVBug 7140899)

# First driver version whose log prefix carries the kernel thread id instead of
# the pthread id: 13.0 prints the pthread id and 13.4 the kernel thread id.
# TODO: confirm the exact version between 13000 and 13040.
cdef int _TID_SWITCH_VERSION = 13040

_driver_log_users = 0
_driver_log_users_lock = threading.Lock()
_driver_log_settings = threading.local() # logger and levels of this thread


cdef int _check_log_call(cydriver.CUresult err) except -1 nogil:
if err != cydriver.CUresult.CUDA_SUCCESS:
with gil:
raise RuntimeError(f"internal cuda.core error, please report: driver log call returned {err}")
return 0


cdef Py_ssize_t _dump_thread_lines(char* buf) except -1 nogil:
# Dumps the messages logged since this thread's mark, advances the mark,
# and keeps this thread's lines in buf.
cdef size_t size = _LOG_DUMP_SIZE
_check_log_call(cydriver.cuLogsDumpToMemory(&cuda_core_driver_log.it, buf, &size, 0))
return cuda_core_keep_thread_lines(buf, size, cuda_core_driver_log.tid)


def _parse_driver_log(lines: bytes) -> list[tuple[str, str]]:
"""Split "[time][tid][lib][E/W] message" lines into (level, message) pairs."""
result = []
for line in lines.decode(errors="backslashreplace").splitlines():
tagged = line.split("]", 3)[3] # "[E] message"
result.append((tagged[1], tagged[3:].strip()))
return result


def _log_driver_messages(lines: bytes) -> None:
settings = _driver_log_settings
for level, message in _parse_driver_log(lines):
settings.logger.log(settings.warn_level if level == "W" else settings.error_level, message)


cdef int _driver_log_after_call(cydriver.CUresult error) except?-1 nogil:
cdef cydriver.CUlogIterator end
cdef char buf[_LOG_DUMP_SIZE + 1]
cdef Py_ssize_t n
if cuda_core_driver_log.mode == _LOG_TO_LOGGER:
_check_log_call(cydriver.cuLogsCurrent(&end, 0))
if end != cuda_core_driver_log.it:
n = _dump_thread_lines(buf)
if n:
with gil:
_log_driver_messages(buf[:n])
if error != cydriver.CUresult.CUDA_SUCCESS:
return _raise_driver_error(error)
return 0


# The level defaults are the values of logging.ERROR and logging.WARNING. They
# are literals so that importing cuda.core reads nothing from logging.
def register(
logger: logging.Logger | None = None,
*,
cuda_error_as: int = 40,
cuda_warn_as: int = 30,
) -> None:
"""Report the CUDA driver's log messages for the calling thread's cuda.core calls.

With a ``logger``, the messages that the driver logs for the calling
thread are passed to ``logger`` after each cuda.core driver call. With
``None``, they are instead attached as notes (``__notes__``) to the
:class:`~cuda.core.CUDAError` that a failing cuda.core driver call raises.
Messages logged before this call are excluded. Calling it again on a
registered thread has no effect.

Parameters
----------
logger : logging.Logger, optional
The logger that receives the messages, or ``None`` for exception notes.
cuda_error_as : int, optional
The logging level of the driver's error messages. Default:
``logging.ERROR``.
cuda_warn_as : int, optional
The logging level of the driver's warning messages. Default:
``logging.WARNING``.

Raises
------
RuntimeError
If the CUDA driver is older than 12.9, which has no log.
"""
global _driver_log_users
cdef int ver
if cuda_core_driver_log.mode:
return
HANDLE_RETURN(cydriver.cuDriverGetVersion(&ver))
if ver < 12090:
raise RuntimeError(f"cuda.core.utils.register requires a CUDA 12.9 or newer driver, found {ver}")
_check_log_call(cydriver.cuLogsCurrent(&cuda_core_driver_log.it, 0))
cuda_core_driver_log.tid = cuda_core_thread_id(ver >= _TID_SWITCH_VERSION)
_driver_log_settings.logger = logger
_driver_log_settings.error_level = cuda_error_as
_driver_log_settings.warn_level = cuda_warn_as
cuda_core_driver_log.mode = _LOG_TO_NOTES if logger is None else _LOG_TO_LOGGER
with _driver_log_users_lock:
_driver_log_users += 1


def unregister() -> None:
"""Stop reporting the driver's log messages for the calling thread.

Undoes :func:`register`. Calling it on a thread that is not registered has
no effect.
"""
global _driver_log_users
if not cuda_core_driver_log.mode:
return
cuda_core_driver_log.mode = 0
_driver_log_settings.logger = None
with _driver_log_users_lock:
_driver_log_users -= 1


cdef int _raise_driver_error(cydriver.CUresult error) except -1 nogil:
cdef const char* name
cdef const char* desc
cdef char log_buf[_LOG_DUMP_SIZE + 1]
cdef Py_ssize_t log_len = 0
if cuda_core_driver_log.mode == _LOG_TO_NOTES:
log_len = _dump_thread_lines(log_buf)
# A context-scoped helper in the handle layer may have recorded why this
# status needs more explanation (e.g. the caller's context was not restored).
cdef const char* detail = take_last_error_detail(error)
Expand All @@ -209,6 +402,10 @@ cdef int _raise_driver_error(cydriver.CUresult error) except -1 nogil:
exc = exc_type(f"{name.decode()}: {desc.decode()}")
if detail != NULL:
_attach_detail(exc, detail.decode())
if log_len:
for _, message in _parse_driver_log(log_buf[:log_len]):
if not message.startswith("Returning "): # already in the message
_attach_detail(exc, "driver log: " + message)
raise exc


Expand Down
3 changes: 3 additions & 0 deletions cuda_core/cuda/core/utils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
StridedMemoryView,
args_viewable_as_strided_memory,
)
from cuda.core._utils.cuda_utils import register, unregister
from cuda.core.utils._program_cache import (
FileStreamProgramCache,
InMemoryProgramCache,
Expand All @@ -38,4 +39,6 @@
"discard_prefetch_batch",
"make_program_cache_key",
"prefetch_batch",
"register",
"unregister",
]
2 changes: 2 additions & 0 deletions cuda_core/docs/source/api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -434,6 +434,8 @@ Utility functions
utils.prefetch_batch
utils.discard_batch
utils.discard_prefetch_batch
utils.register
utils.unregister

:template: autosummary/cyclass.rst

Expand Down
9 changes: 9 additions & 0 deletions cuda_core/docs/source/release/1.4.0-notes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,15 @@
``cuda.core`` 1.4.0 Release Notes
=================================

New features
------------

- :func:`utils.register` reports the CUDA driver's log messages for the
calling thread's ``cuda.core`` calls, either to a :class:`logging.Logger` or
as notes on the :class:`CUDAError` that a failing call raises.
:func:`utils.unregister` stops it. Requires a CUDA 12.9 or newer driver.
(`#671 <https://github.com/NVIDIA/cuda-python/issues/671>`__)

Fixes and enhancements
----------------------

Expand Down
Loading
Loading