cuda-python / cuda_core
AGENTS.md3.4k starsChanged 4 months agoApache-2.0View on GitHub
This file describes cuda_core, the high-level Pythonic CUDA subpackage in the cuda-python monorepo. - Role: provide higher-level CUDA abstractions (Device, Stream, Program, Linker, memory resources, graphs) on top of cuda.bindings. - API intent: keep interfaces Pythonic while preserving explicit CUDA behavior and error visibility. - Compatibility: changes should remain compatible with supported cuda.bindings major versions (12.x and 13.x). - Main package: cuda/core/ contains most Cython modules (*.pyx, *.pxd) implementing runtime behaviors and public objects. - Subsystems: - memory/resource stack: cuda/core/_memory/…
Trending
More talk lately.thin dataabout the whole repository
Who's talking about NVIDIA/cuda-python
- rapidsai/rmm“Replace use of custom CUDA bindings with CUDA-Python”GitHub · Dec 3, 2021 · 12 reactions
- jungwoo-ha/WeeklyArxivTalk“[20210815] Weekly AI ArXiv 만담”GitHub · Aug 14, 2021 · 12 reactions
- A Hacker News story“CUDA Python Low-Level Bindings”Hacker News · Aug 21, 2021 · 4 points
- pytorch/pytorch“RFC: The State of Custom CUDA extensions in PyTorch”GitHub · Apr 23, 2025 · 3 reactions
- apache/arrow“POC: [Python] try out stubgen-pyx for auto-generated typing stubs”GitHub · Oct 1, 2026 · 2 reactions
The biggest 5 of 12 mentions linking to the repository that our crawl found. Each line is their own headline.
See all 12
Talked about on GitHub, Hacker News and Bluesky (12 times).
On GitHub · 10
- Dec 3, 2021Replace use of custom CUDA bindings with CUDA-Python — rapidsai/rmm12 reactions · 16 comments
- Aug 14, 2021[20210815] Weekly AI ArXiv 만담 — jungwoo-ha/WeeklyArxivTalk12 reactions · 3 comments
- Apr 23, 2025RFC: The State of Custom CUDA extensions in PyTorch — pytorch/pytorch3 reactions · 29 comments
- Oct 1, 2026POC: [Python] try out stubgen-pyx for auto-generated typing stubs — apache/arrow2 reactions · 4 comments
- Apr 11, 2026Allow getting `AtenTensorHandle` from the tensor object via AOTI stable C API — pytorch/pytorch2 reactions · 6 comments
5 more on GitHub
- Oct 5, 2026deps: bump the python-minor group with 8 updates — pcalnon/juniper-cascor1 reaction · 1 comment
- Jul 19, 2026chore(deps): bump cuda-bindings from 13.2.0 to 13.3.1 — grisuno/LazyOwn1 reaction · 1 comment
- Mar 2, 2026CuPy fails to auto-detect CUDA when CUDA_PATH is unset in containers (RawKernel / JIT compile) — cupy/cupy1 reaction · 1 comment
- Feb 10, 2026[FEA] Migrate RAPIDS to CCCL `cuda::stream_ref` / `cuda::stream` in C++ and `cuda.core` streams in Python — rapidsai/rmm1 reaction · 1 comment
- Sep 19, 2025RFC: Support CUDA Stream Protocol — rapidsai/rmm1 reaction · 6 comments
On Hacker News · 1
- Aug 21, 2021CUDA Python Low-Level Bindings4 points
On Bluesky · 1
- Apr 9, 2025📦 NVIDIA / cuda-python ⭐ 1,537 (+50) 🗒 Python CUDA Python: Performance meets Productivity — @github-trending.bsky.social2 likes and reposts
Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about checking a change actually works.
Of the AGENTS.md files we read, the 11,773 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repository13 other files it gives its agents.
- AGENTS.mdAGENTS.md
- benchmarks/cuda_bindings/AGENTS.mdAGENTS.md
- benchmarks/cuda_core/AGENTS.mdAGENTS.md
- cuda_bindings/AGENTS.mdAGENTS.md
- cuda_core/tests/AGENTS.mdAGENTS.md
- cuda_pathfinder/AGENTS.mdAGENTS.md
- cuda_python/AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- cuda_bindings/CLAUDE.mdCLAUDE.md
- cuda_core/CLAUDE.mdCLAUDE.md
- cuda_pathfinder/CLAUDE.mdCLAUDE.md
- cuda_python/CLAUDE.mdCLAUDE.md
- create-cuda-python-pull-requestSkill
The file
We split this AGENTS.md into the rules it gives an agent
11 rules. About 0 are common, 6 are distinctive, and 5 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈6
Distinctive · estimate
This author's own choices. Worth a look.
5
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 8
API intent: keep interfaces Pythonic while preserving explicit CUDA behavior and error visibility.
- Very specific: line 54
Check ci/versions.yml. The build pin is the current major and the prev_build pin is the prior major.
- Very specific: line 61
Add to the release notes a "Breaking Changes" entry that names the new floors.
- Distinctive: line 64
If the pins moved past what the pixi lock files resolve, refresh the lock files.
- Distinctive: line 115
Keep user-facing behaviors coherent with docs and examples, especially around stream semantics, memory ownership, and compile/link flows.
- Very specific: line 119
When changing Cython signatures or cimports, verify related .pxd and call-site consistency.
- Distinctive: line 121
Prefer explicit error propagation over silent fallback paths.
- Very specific: line 122
If you change public behavior, update tests and docs under docs/source/.
- Distinctive: line 190
Publish before you raise: when a driver mutation has succeeded and a later step can still fail, commit whatever keeps that mutation …
- Distinctive: line 284
Make sure conceptual pairs match, e.g.
- Very specific: line 292
Instead, a new StrEnum subclass should be used to define the values.
≈ “Common” is an estimate: at least 1 in 5 of the 16,595 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
This file describes cuda_core, the high-level Pythonic CUDA subpackage in the
cuda-python monorepo.
Scope and principles
- Role: provide higher-level CUDA abstractions (
Device,Stream,Program,Linker, memory resources, graphs) on top ofcuda.bindings. - API intent: keep interfaces Pythonic while preserving explicit CUDA behavior and error visibility.
- Compatibility: changes should remain compatible with supported
cuda.bindingsmajor versions (12.x and 13.x).
Package architecture
- Main package:
cuda/core/contains most Cython modules (*.pyx,*.pxd) implementing runtime behaviors and public objects. - Subsystems:
- memory/resource stack:
cuda/core/_memory/ - system-level APIs:
cuda/core/system/ - compile/link path:
_program.pyx,_linker.pyx,_module.pyx - execution path:
_launcher.pyx,_launch_config.pyx,_stream.pyx
- memory/resource stack:
- C++ helpers: module-specific C++ lives under
cuda/core/_cpp/, either as one_cpp/<name>.cppor as a directory_cpp/<name>/whose sources all compile into the_<name>extension (_cpp/rt/for_rt). - Build backend:
build_hooks.pyhandles Cython extension setup and build dependency wiring.
Build and version coupling
build_hooks.pydetermines CUDA major version fromCUDA_CORE_BUILD_MAJORor CUDA headers (CUDA_HOME/CUDA_PATH) and uses it for build decisions.- Source builds require CUDA headers available through
CUDA_HOMEorCUDA_PATH. cuda_corerequirescuda-bindingsat or above a per-major floor at build time and at run time. At build time it also requires acuda.hof the same major.minor as thatcuda-bindings(NVIDIA/cuda-python#2783). The floors are declared once, by thecu12/cu13extras inpyproject.toml(cuda-bindings[all]>=<floor>,<<next major>).build_hooks.py, the import-time check incuda/core/__init__.py, the docs and CI read them from there throughcuda/core/_bindings_floor.py. The C++ branches onCUDA_CORE_BUILD_MAJORonly. Whether a feature is available at run time depends on the driver alone, never on thecuda-bindingsversion.
Bumping the cuda-bindings floor
By policy, the floor of each major is the newest cuda-bindings release of
that major at the time of a cuda.core release. The bump is therefore a
release step. A cuda-bindings minor release does not trigger it. The first
change that uses a cuda-bindings API newer than the old floor also requires
a bump. To bump:
- Edit the
cuda-bindingspin in thecu12orcu13extra inpyproject.toml. That is the only version to type. - Check
ci/versions.yml. Thebuildpin is the current major and theprev_buildpin is the prior major. Neither toolkit pin may sit below its floor's major.minor, or CI builds a configuration that the build rejects. A toolkit ahead of the floor is the bump window described below. The pre-commit hookcheck-cuda-core-bindings-floor(toolshed/check_cuda_core_bindings_floor.py) checks the pins. It also checks that no documentation page spells a floor out by hand. - Add to the release notes a "Breaking Changes" entry that names the new
floors. The support-policy table in
docs/source/support.rstreads the floors and the release version at docs-build time. It needs no edit. - If the pins moved past what the pixi lock files resolve, refresh the lock files.
- Pin
cuda-bindingsto match in the conda-forgecuda-corefeedstock. The feedstock lives outside this repository.
A cuda-core release also bumps the cuda-core~=X.Y.0 pin in
cuda_python/setup.py, followed by a cuda-python release (see
.github/RELEASE-core.md).
CUDA Toolkit minor bumps
The build compares the toolkit's cuda.h with the header that the installed
cuda-bindings was generated from (cuda.bindings.driver.CUDA_VERSION). It
does not compare version strings. The commit that moves ci/versions.yml to a
new minor therefore builds cuda.core against the cuda-bindings built from
the same commit. Isolated builds request cuda-bindings no newer than the
toolkit's minor, a cap that admits that development build. The import-time
check compares headers the same way.
The floor stays where it is until a cuda-bindings release of the new minor
exists on PyPI. Until then, the CI rows that install the literal floor
(BINDINGS_SOURCE=floor) fail the header check and stay red. That window is
accepted. Do not add fallback logic for it. The order is:
- Bump the toolkit.
- Release
cuda-bindingsfor the new minor. - Bump the floor here.
Testing expectations
- Primary tests:
pytest tests/ - Cython tests:
- build:
tests/cython/build_tests.sh(or platform equivalent) - run:
pytest tests/cython/
- build:
- Examples: validate affected examples in
examples/when changing user workflows or public APIs.
Runtime/build environment notes
- Runtime env vars commonly relevant:
CUDA_PYTHON_CUDA_PER_THREAD_DEFAULT_STREAMCUDA_PYTHON_DISABLE_MAJOR_VERSION_WARNING
- Build env vars commonly relevant:
CUDA_HOME/CUDA_PATHCUDA_CORE_BUILD_MAJORCUDA_PYTHON_PARALLEL_LEVELCUDA_PYTHON_COVERAGECUDA_PYTHON_WERROR(compiler warnings become errors; CI wheel builds set it)
Editing guidance
- Keep user-facing behaviors coherent with docs and examples, especially around stream semantics, memory ownership, and compile/link flows.
- Reuse existing shared utilities in
cuda/core/_utils/before adding new helpers. - When changing Cython signatures or cimports, verify related
.pxdand call-site consistency. - Prefer explicit error propagation over silent fallback paths.
- If you change public behavior, update tests and docs under
docs/source/.
Concurrency and free-threading
cuda.core ships free-threaded (no-GIL) wheels and builds with
freethreading_compatible=True. The user-facing policy lives in
docs/source/concurrency.rst; the invariants below are for contributors. Reviewers
and agents should flag violations.
- Reads are safe; mutation is the boundary: concurrent reads of an object are
supported, but concurrent mutation of the same public object (e.g., building one
graph from two threads, or
close()racing another call) is the caller's responsibility -- do not add locks to make it safe. Prefer immutable designs to keep the mutable, thread-unsafe surface small. Protecting library-internal state is in scope. - Distinct objects can still collide via shared driver state: operating on separate objects is not automatically safe when they share driver or context state (e.g., changing peer device access while another thread touches affected memory). Synchronizing these cases is the caller's responsibility; do not try to lock around them internally.
- Protect internal cached/module-level state: guard lazily-populated
cdef objectcaches and module-level state so concurrent access cannot corrupt interpreter state (CPython reference counts -- a strictly free-threading hazard). Established patterns are@cython.critical_sectionon accessors (#2215), an atomic initialization flag (#2216), anddict.setdefaultfor identity caches (#2217). Guard state only on objects that are legitimately shared between threads; objects that are not meant to be shared (e.g., the thread-localDevice) do not need such guards (see #2321). Reference-count integrity is guaranteed; cache value-identity/idempotency is not. - Entry points work with or without the GIL: Cython calls the helpers in
_cpp/rt/both inside and outsidewith nogilblocks. They never require the GIL, release it around driver calls, and never acquire it while they hold a C++ lock. The only paths that acquire it are the reporting wrappers (pw_*,report_*) and the one-time driver function-table fill (ensure_fn_table(), see_cpp/rt/DESIGN.md). Driver and destructor callbacks run at arbitrary times, so they take the GIL (with gil) and probe for interpreter shutdown before touching Python objects. - Driver calls go through the table: C++ calls the driver with
DRIVER_CALL(name, args...). Its pointers come from the table that cuda-bindings resolves, never from the Cython wrappers. If the installed driver may lack a function, Cython gates it oncy_driver_version()at the version cuda-bindings requests it at (the number indriver_api.hpp). The C++ never checks a pointer for null. - Lock ordering -- release the GIL before entering the driver: any CUDA work
reachable from a host callback or a retained object's
__del__must release the GIL before calling the driver, to avoid GIL/driver-lock deadlocks (see the_py_host_trampolinepath and numba-cuda#321). Objects retained into a graph (kernel arguments, memcpy/memset operands,dst_owner/src_owner, and host-callback closures) inherit this contract.
Failure handling
The user-facing contract lives in docs/source/error_handling.rst; the rules
below are for contributors. Reviewers and agents should flag violations.
- Raise by default: any failure on a path where an exception can propagate
raises. Driver statuses go through
HANDLE_RETURN(Cython) or are returned asCUresultfrom the C++ handle layer and thenHANDLE_RETURNed; never replace aCUresultwith a genericRuntimeError, and drainget_last_error()immediately after a handle constructor returns empty so a stale status cannot be misattributed later. - Guarantees: a call that creates a resource must create nothing when it
raises (undo the creation if a later step fails). Every call except
Device.set_currentmust leave the calling thread's current context as it found it. Do not hand-rollcuCtxPush/Pop/SetCurrentsequences in Cython; use the handle layer's scoped-context helpers (invoke_in_context,invoke_in_context_or_undo,cleanup_in_context,context_get_device,graph_node_set_params) so the failure handling exists in one place. - Publish before you raise: when a driver mutation has succeeded and a later step can still fail, commit whatever keeps that mutation memory-safe (for example the graph attachment that retains a node's new owners) before raising the later error. Rolling back the retention of a live mutation creates a dangling reference. When ownership cannot be established, retain the resources anyway (leak) rather than release them; a leak is always preferred to a use-after-free.
- Non-propagating paths never raise and never discard a status: shared_ptr
deleters,
__dealloc__and CUDA callbacks report through one channel,report_cuda_error()/report_message()in C++ (thepw_*wrappers) orwarnings.warn(..., CUDAWarning)in Cython and Python, which emitscuda.core.CUDAWarning. Noprint(file=sys.stderr)and nofprintfoutside that helper.CUDA_ERROR_DEINITIALIZEDis filtered by the helper because it means the driver is shutting down. - Pick the channel by where you are: a path that can raise uses
HANDLE_RETURN; anexceptblock whose rollback failed usesattach_rollback_failure(); a deleter or cleanup path uses apw_*wrapper orreport_cuda_error(); the same situation in Cython or Python useswarnings.warn(..., CUDAWarning); a CUDA callback thread does nothing that needs the GIL and hands its work to the deferred-cleanup queue (Py_AddPendingCallis GIL-free and allowed there). The table in_cpp/rt/DESIGN.md("Which channel to use") spells this out. pw_*runs user Python: ap_pointer only calls the driver; itspw_twin also acquires the GIL on failure and runs the warning filters,showwarning, orsys.unraisablehook, any of which may call back into cuda.core. Never call apw_*wrapper orreport_*while holding a C++ lock. Take the GIL as the outermost lock, release it before taking a C++ lock, and when a lock must stay held callp_, keep the status, and report after the lock is released (deviceptr_import_ipcis the model).- Rollback failure: the original exception propagates; the failed rollback
is attached to it with
attach_rollback_failure()(a PEP 678 note on Python 3.11+, reported out-of-band on 3.10), or chained withraise ... fromwhen a second exception must be raised. Catching everything (bareexcept:orexcept BaseException:) is acceptable only for rollback-then-raiseblocks, where the rollback must also run forKeyboardInterrupt. - Finalization: once
py_is_finalizing()is true, do no Python work from destructors or callbacks and accept the leak (see_cpp/rt/py.hppand_cpp/rt/GRAPH_ATTACHMENTS.md). - Never terminate the process: no
std::abort,std::terminate,exit,Py_FatalError, orassertthat survives into a release build, anywhere incuda.core. A failed CUDA call, including a failed context restoration, is raised or reported. An internal invariant violation is handled the same way: raise aRuntimeErrorthat says "internal cuda.core error, please report" where an exception can propagate, report through the channel above where it cannot, and leak the affected resource rather than touch state that may be inconsistent. Users who want fail-fast behavior get it withwarnings.filterwarnings("error", category=CUDAWarning)andPYTHONFAULTHANDLER; the library does not make that choice for them. An implicit abort (an exception escaping anoexceptfunction or a deleter, includingstd::bad_allocfrom an allocation insidenoexceptcode) is a bug (#1489, #2417), not a policy choice:noexcepthelpers must not allocate, or must catch what they call. - Testing: inject restoration failures with
cuda.core._rt._set_context_restore_fault_for_testing; assert reports withpytest.warns(CUDAWarning)orwarnings.catch_warnings, never by matching stderr text.
API design guidelines
These are some API design guidelines we try to follow when adding new APIs to
cuda.core. These rules only apply to public APIs. Private implementation
details can violate these rules at any time.
Public APIs are defined as symbols defined in __all__ within modules or
subpackages that are not prefixed with _.
In code reviews, any violations of this section should be considered suggestions, not hard rules. Consistency with existing API design in this code base is also important.
Unintentional exposure of symbols
The following things should not be exposed as part of the public API:
- Private symbols (prefixed with
_) - Symbols from a third-party module or the standard library
- Helper classes that can not be instantiated from Python
Naming
As a blanket rule, we follow the naming guidelines for capitalization in PEP 8.
Naming should be consistent. We should use the same English words for the same concepts throughout the public API. When abbreviations are used, they should be commonly understood, and they should also be used consistently across the public API.
For all attributes of a class:
- Properties and member variables should be nouns
- Methods should be verbs
- Methods that take no arguments, are idempotent and cheap (O(1) or trivial), and do not mutate observable state should be properties
Make sure conceptual pairs match, e.g. add/remove, get/set, create/delete, alloc/free.
Free functions should be verbs.
Enumerations
Enumerations from the underlying cuda_bindings should not be re-exposed.
Instead, a new StrEnum subclass should be used to define the values. Anywhere
a StrEnum is accepted as an argument, a str should also be acceptable. An
invalid value should raise an exception. When a function returns a str drawn
from a small number of values, return a StrEnum subclass instead.
For __post_init__ validation in frozen dataclasses, use the
not isinstance(value, EnumType) → try EnumType(value) except (ValueError,
TypeError) pattern (modelled on _normalize_enum in
cuda/core/texture/_texture.pyx). This accepts the enum itself or a valid
string, and raises ValueError eagerly for any other type rather than
silently storing it.
Exception handling
Raising exceptions is preferred over a C-style return code that must be checked by the user.
Type annotations
Python or Cython type annotations should be included for all public APIs. Avoid
the use of Any unless absolutely necessary. The argument and return types as
defined in the docstrings should match the type annotations.
Python imports should generally be outside of an if typing.TYPE_CHECK: block, even if the imported object is only used in type annotations. Use if typing.TYPE_CHECK: only to avoid creating import cycles. (This guidance maximizes compatibility with the cross-reference mechanisms in Sphinx.)
Semantics
APIs should exist for both manual resource management (such as close()) and
automatic resource management, using context managers or destructors where
appropriate. Context managers should be implemented with __enter__ and
__exit__, not contextlib.contextmanager. For destructors use __dealloc__
where possible, otherwise __del__.
Documentation
The entirety of the public API should be documented in api.rst or one of the
subpages linked from it. Classes that are not directly instantiable but which
may be returned through the public API should be documented in api_private.rst
so that they are documented but don't appear in the main index.
API stability
Reviews should point out where existing public APIs are broken.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

