cuda-python / tests
AGENTS.md3.4k starsChanged 4 months agoApache-2.0View on GitHub
Package-wide conventions live in ../AGENTS.md; repository-wide ones in ../../AGENTS.md. This file covers conventions specific to the tests. A memory pool created without max_size reserves virtual address space similar in size to the installed physical device memory regardless of what the test actually allocates. The reservation is charged to the process address space even though it is not backed by physical memory, and it is not returned until the pool is destroyed and the stream-ordered frees of its outstanding allocations retire.…
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/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
Show its rules and text
We split this AGENTS.md into the rules it gives an agent
15 rules. About 0 are common, 2 are distinctive, and 13 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈2
Distinctive · estimate
This author's own choices. Worth a look.
13
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 16
When a test needs its own pool, use the suite-wide cap from helpers/constants.py:
- Very specific: line 25
Use a larger value only if a test genuinely requires it, and prefer adding a shared constant to helpers/constants.py over redefining one …
- Very specific: line 41
Do not add max_size to a call that currently passes no options: that converts a free default-pool wrapper into a new pool and makes things …
- Very specific: line 52
When a call is deliberately exempt -- most often because it sits inside pytest.raises and no pool is ever created -- annotate it:
- Distinctive: line 73
Follow these rules when adding or moving shared test code:
- Very specific: line 75
Never import from a conftest.py.
- Very specific: line 76
Put suite-wide fixtures and pytest hooks in tests/conftest.py.
- Very specific: line 78
Put a pytest hook in a nested conftest.py only if pytest supports that hook there.
- Very specific: line 84
Import helpers explicitly from the test root, for example: from helpers.memory import create_managed_memory_resource_or_skip.
- Very specific: line 86
Search tests/helpers/ and cuda_python_test_helpers/ for prior art before adding a new helper.
- Very specific: line 94
Do not add __init__.py solely because a test directory contains a conftest.py.
- Very specific: line 137
When a CUDA call's error means "feature refused by this driver" (e.g.
- Very specific: line 150
Before adding importorskip, check cuda_core/pyproject.toml's test and test-cu* groups and cuda_core's dependencies.
- Very specific: line 201
Do not catch ImportError for a hard runtime dependency (e.g.
- Distinctive: line 207
If a setup step allocates a resource (GL object, window, file handle) and a later step fails, clean up the partial resource before …
≈ “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
cuda.core test suite
Package-wide conventions live in ../AGENTS.md; repository-wide ones in
../../AGENTS.md. This file covers conventions specific to the tests.
Never create an uncapped memory pool
A memory pool created without max_size reserves virtual address space similar
in size to the installed physical device memory regardless of what the test
actually allocates. The reservation is charged to the process address space
even though it is not backed by physical memory, and it is not returned until
the pool is destroyed and the stream-ordered frees of its outstanding
allocations retire. The whole suite shares one process and one device, so these
reservations accumulate across tests.
When a test needs its own pool, use the suite-wide cap from
helpers/constants.py:
from helpers.constants import POOL_SIZE
mr = DeviceMemoryResource(dev, DeviceMemoryResourceOptions(max_size=POOL_SIZE))Use a larger value only if a test genuinely requires it, and prefer adding a
shared constant to helpers/constants.py over redefining one per module.
Passing no options is different from passing empty options
DeviceMemoryResource(dev) with no options does not create a pool. It
wraps the device's existing default mempool (_mempool_owned is false) and
costs no additional address space. Passing any options object creates a new
owned pool, and a new pool without max_size is uncapped:
DeviceMemoryResource(dev) # wraps default pool, free
DeviceMemoryResource(dev, DeviceMemoryResourceOptions()) # NEW uncapped pool, expensive
DeviceMemoryResource(dev, {"ipc_enabled": True}) # NEW uncapped pool, expensiveDo not add max_size to a call that currently passes no options: that
converts a free default-pool wrapper into a new pool and makes things worse.
Managed pools are exempt
cuMemPoolCreate requires CUmemPoolProps.maxSize to be zero for managed
pools, so ManagedMemoryResourceOptions has no max_size option. Managed
pools cannot be right-sized and are not checked.
Document exemptions
When a call is deliberately exempt -- most often because it sits inside
pytest.raises and no pool is ever created -- annotate it:
with pytest.raises(RuntimeError, match="IPC is not available"):
# uncapped-pool-ok: raises before the pool is created
DeviceMemoryResource(mempool_device, DeviceMemoryResourceOptions(ipc_enabled=True))Release resources at test boundaries
The init_cuda fixture in conftest.py runs gc.collect() followed
by cuCtxSynchronize() before popping the context. Tests should not rely on
that as a substitute for cleaning up explicitly: prefer context managers for
resources whose lifetime fits a single scope, and keep pool lifetimes inside
the test that creates them.
Shared test support
Follow these rules when adding or moving shared test code:
- Never import from a
conftest.py. - Put suite-wide fixtures and pytest hooks in
tests/conftest.py. Put fixtures needed only by one test subtree in that subtree's nearestconftest.py. - Put a pytest hook in a nested
conftest.pyonly if pytest supports that hook there. If the hook receives suite-wide data, explicitly limit its effects to the intended subtree. - Code used only to implement fixtures or hooks may remain in the same
conftest.py. Put functions and constants imported by test modules intests/helpers/instead. - Import helpers explicitly from the test root, for example:
from helpers.memory import create_managed_memory_resource_or_skip. Search
tests/helpers/andcuda_python_test_helpers/for prior art before adding a new helper; consolidate duplicates acrosspackages into
cuda_python_test_helpers(bothcuda_coreandcuda_bindingstest environments already depend on it).- Fixtures in a nested
conftest.pyare available to tests in its directory and descendants; fixtures from applicable parentconftest.pyfiles remain available. - Do not add
__init__.pysolely because a test directory contains aconftest.py. - In directories without
__init__.py, keep test-module basenames unique within this test suite.
Skip only real setup failures
pytest.skip(reason) records the test as SKIPPED with reason in the
report. A helper that wraps yield in except Exception: pytest.skip(...)
therefore records every test-body failure as a skip — a real regression, a
TypeError, an AttributeError all become "SKIPPED: <reason>" instead of
"FAILED", and the suite goes green regardless of whether the code under
test works.
Catch only the specific exception that legitimately means "not available",
and only around the setup call — never around yield:
@contextlib.contextmanager
def _gl_context():
try:
win, tex_id = _setup_gl_texture() # setup only
except (pyglet.NoSuchConfigException, GLContextError) as e:
pytest.skip(f"GL unavailable: {e}")
try:
yield tex_id # body exceptions propagate
finally:
_cleanup(win, tex_id)The exception names in the example are illustrative — GLContextError
is not a real pyglet class. Match real pyglet exception names by type, or
use the shared is_gl_context_unavailable helper in
cuda_python_test_helpers.graphics.
GLException is pyglet's generic GL-error class, raised after any GL call that reports an error
(GL_INVALID_ENUM, etc.). Do not include it in the "GL unavailable" set — it hides real bugs in GL allocation code as skips.
Platform-specific "library not loadable" manifestations (genuine "GL unavailable"):
- Linux without libGL/libEGL:
ImportError('Library "GL" not found.')/ImportError('Library "EGL" not found.')frompyglet/lib.py. - Windows without opengl32.dll:
FileNotFoundErrorfromctypes.windll.opengl32; on Python 3.12+ctypes.LibraryLoaderre-raisesAttributeError("opengl32").
When a CUDA call's error means "feature refused by this driver" (e.g.
CUDA_ERROR_OPERATING_SYSTEM for CUDA-GL interop on WSL), skip at the call
site with a narrow catch on the specific error, not inside the GL helper —
see _register_gl_buffer / _register_gl_image in tests/test_graphics.py.
importorskip is for optional dependencies only
pytest.importorskip("X") is correct when X is genuinely optional
(platform-gated binding, parametrized "test each available module"). It is
dead code when X is a declared test or runtime dependency: the skip then
fires only when the environment is broken, which is the case you want to fail
loudly, not hide. Use a bare top-level import for declared deps.
Before adding importorskip, check cuda_core/pyproject.toml's test
and test-cu* groups and cuda_core's dependencies. If the target is
listed, import it directly.
Capability probes must not swallow real bugs
A probe function that answers "is feature X available?" by catching
Exception and returning False will report "not available" even when the
probed API failed for a real, unexpected reason — silently enabling a skip
that hides the bug. Catch only the exception that genuinely means "not
available", and split the checks so each catch is narrow:
def _is_nvfatbin_available():
from cuda.bindings._internal.utils import FunctionNotFoundError
from cuda.pathfinder import DynamicLibNotFoundError
try:
from cuda.bindings import nvfatbin
except ImportError:
return False
try:
nvfatbin.version()
except (DynamicLibNotFoundError, FunctionNotFoundError):
# libnvfatbin not loadable, or nvFatbinVersion symbol missing.
return False
return TrueCatch only the exceptions that mean "not installed / not loadable".
A genuine API-status failure (e.g. nvfatbin.nvFatbinError from a
successfully loaded library) must propagate so a real bug is not hidden
as "unavailable".
For a probe that calls a CUDA API returning a CUresult, let handle_return
raise on any non-success result and classify only a successful bitmask
lacking the documented bit as False; other failures propagate so a real driver bug is not hidden as "unsupported":
@functools.cache
def supports_ipc_mempool(device_id):
from cuda.bindings import driver
handle_return(driver.cuInit(0))
dev_id = int(getattr(device_id, "device_id", device_id))
attr = driver.CUdevice_attribute.CU_DEVICE_ATTRIBUTE_MEMPOOL_SUPPORTED_HANDLE_TYPES
mask = handle_return(driver.cuDeviceGetAttribute(attr, dev_id))
posix_fd = driver.CUmemAllocationHandleType.CU_MEM_HANDLE_TYPE_POSIX_FILE_DESCRIPTOR
return (int(mask) & int(posix_fd)) != 0Do not catch ImportError for a hard runtime dependency (e.g.
cuda.bindings for cuda.core) — that is a broken environment and should
surface at collection time.
Clean up partial setup on failure
If a setup step allocates a resource (GL object, window, file handle) and a later
step fails, clean up the partial resource before re-raising so it does not
leak. Wrap the allocation in try/except and delete the generated object in
the except before re-raising:
def _allocate_gl_buffer(win, nbytes):
from pyglet.gl import gl as _gl
buf_id = _gl.GLuint(0)
try:
_gl.glGenBuffers(1, ctypes.byref(buf_id))
_gl.glBindBuffer(_gl.GL_ARRAY_BUFFER, buf_id.value)
_gl.glBufferData(_gl.GL_ARRAY_BUFFER, nbytes, None, _gl.GL_DYNAMIC_DRAW)
return buf_id
except Exception:
if buf_id.value:
with contextlib.suppress(Exception):
_gl.glDeleteBuffers(1, ctypes.byref(buf_id))
raiseInitialize handles to None before the protected region so the finally
cleanup does not NameError when allocation raises before returning a handle.
Tests that touch CUDA must establish their own context
The init_cuda fixture pops the CUDA context on teardown, so a test
that calls a CUDA API without init_cuda (or an explicit
Device.set_current()) inherits whatever context the previous test happened
to leave current on the thread — possibly none. With pytest-randomly that
makes the pass/fail outcome depend on test order, so it moves seed to seed and
looks like flakiness. Request init_cuda for any test that calls into the
driver, or set up and tear down a context yourself.
Assert on behavior, not implementation
Pin on observable behavior the contract guarantees — return values, raised exception types, public state transitions. Avoid asserting on internal call counts, private helper invocation order, or error message substrings that are not part of the contract. A refactor that preserves behavior but changes internals should not break the test.
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.

