Skip to content
Open
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
6 changes: 0 additions & 6 deletions cuda_bindings_13/tests/example_tests/run_samples.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,6 @@
DEFAULT_SAMPLES_DIR = REPO_ROOT / "samples" / "cuda_bindings"
SAMPLE_NAMESPACE = "cuda_bindings"

build_run_plan = _runner.build_run_plan
collect_sample_entries = _runner.collect_sample_entries
get_gpu_count = _runner.get_gpu_count
load_config = _runner.load_config
run_sample = _runner.run_sample


def main(argv: list[str] | None = None) -> int:
return _runner.main(
Expand Down
40 changes: 5 additions & 35 deletions cuda_bindings_13/tests/example_tests/test_samples.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,52 +5,22 @@
from __future__ import annotations

import os
import sys

import pytest
from run_samples import (
DEFAULT_CONFIG,
DEFAULT_SAMPLES_DIR,
SAMPLE_NAMESPACE,
build_run_plan,
collect_sample_entries,
get_gpu_count,
load_config,
run_sample,
)
from cuda_python_test_helpers.sample_runner import SampleSuite
from run_samples import DEFAULT_CONFIG, DEFAULT_SAMPLES_DIR, SAMPLE_NAMESPACE

_ENTRIES = collect_sample_entries(DEFAULT_SAMPLES_DIR, SAMPLE_NAMESPACE)
_SAMPLES = sorted(_ENTRIES)
_CONFIG = load_config(DEFAULT_CONFIG)
_GPU_COUNT = get_gpu_count() if _SAMPLES else 0
_SUITE = SampleSuite(DEFAULT_SAMPLES_DIR, SAMPLE_NAMESPACE, DEFAULT_CONFIG)
_CUDA_12_PIXI_ENV = os.environ.get("PIXI_ENVIRONMENT_NAME") == "cu12"


@pytest.mark.parallel_threads_limit(1)
@pytest.mark.parametrize("sample_key", _SAMPLES)
@pytest.mark.parametrize("sample_key", _SUITE.keys)
@pytest.mark.samples
@pytest.mark.skipif(
_CUDA_12_PIXI_ENV,
reason="cuda.bindings samples require cuda-python 13 or newer",
)
@pytest.mark.agent_authored(model="gpt-5")
def test_sample(sample_key: str) -> None:
if _GPU_COUNT == 0:
pytest.skip("No CUDA GPU detected on the test runner")

entry = _ENTRIES.get(sample_key)
if entry is None or not entry.is_file():
pytest.fail(f"Sample entrypoint missing: {sample_key}")

plan = build_run_plan(entry, _CONFIG, _GPU_COUNT, sample_key=sample_key)
result = run_sample(plan)

if result.status == "WAIVED":
if result.detail.startswith("unmet package requirement(s):"):
pytest.fail(f"sample dependencies are not satisfied: {result.detail}")
pytest.skip(result.detail or "sample waived")
if result.status == "PASS":
return

sys.stdout.flush()
pytest.fail(f"sample {sample_key} returned status={result.status} (rc={result.return_code}): {result.detail}")
_SUITE.check(sample_key, fail_on_unmet_dependencies=True)
10 changes: 3 additions & 7 deletions cuda_core/tests/example_tests/run_samples.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,20 +19,16 @@
DEFAULT_SAMPLES_DIR = REPO_ROOT / "samples" / "cuda_core"
SAMPLE_NAMESPACE = "cuda_core"

DEFAULT_TIMEOUT = _runner.DEFAULT_TIMEOUT
DependencyMetadataError = _runner.DependencyMetadataError
# Re-exported for the runner unit tests in test_run_samples.py and
# test_sample_verification.py.
RunPlan = _runner.RunPlan
RunResult = _runner.RunResult
build_run_plan = _runner.build_run_plan
collect_sample_entries = _runner.collect_sample_entries
discover_samples = _runner.discover_samples
get_gpu_count = _runner.get_gpu_count
get_sample_id = _runner.get_sample_id
load_config = _runner.load_config
missing_dependencies = _runner.missing_dependencies
run_sample = _runner.run_sample

# Kept available for runner unit tests that patch distribution metadata.
# Patched by the runner unit tests to fake distribution metadata.
importlib = _runner.importlib


Expand Down
1 change: 1 addition & 0 deletions cuda_core/tests/example_tests/test_run_samples.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
class _Distribution:
def __init__(self, version: str, extras: tuple[str, ...] = ()) -> None:
self.version = version
self.requires = None
self.metadata = Message()
for extra in extras:
self.metadata["Provides-Extra"] = extra
Expand Down
45 changes: 6 additions & 39 deletions cuda_core/tests/example_tests/test_samples.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,26 +4,11 @@

from __future__ import annotations

import sys

import pytest
from run_samples import (
DEFAULT_CONFIG,
DEFAULT_SAMPLES_DIR,
SAMPLE_NAMESPACE,
build_run_plan,
collect_sample_entries,
get_gpu_count,
load_config,
run_sample,
)
from cuda_python_test_helpers.sample_runner import SampleSuite
from run_samples import DEFAULT_CONFIG, DEFAULT_SAMPLES_DIR, SAMPLE_NAMESPACE

_ENTRIES = collect_sample_entries(DEFAULT_SAMPLES_DIR, SAMPLE_NAMESPACE)
_SAMPLES = sorted(_ENTRIES)
_CONFIG = load_config(DEFAULT_CONFIG)
# Resolve GPU count once at collection time so we report the same skip reason
# consistently across the parametrized test ids.
_GPU_COUNT = get_gpu_count() if _SAMPLES else 0
_SUITE = SampleSuite(DEFAULT_SAMPLES_DIR, SAMPLE_NAMESPACE, DEFAULT_CONFIG)


# Samples launch full GPU workloads in their own subprocess, so keep them
Expand All @@ -32,30 +17,12 @@
# cuda_core/customTensorFlowKernel, cuda_core/fftSignalAnalysis, cuda_core/glInteropFluidNumbaCudaMlir,
# cuda_core/glInteropFluid, cuda_core/glInteropMipmapLod, cuda_core/glInteropPlasma, cuda_core/greenContext,
# cuda_core/matrixMulSharedMem, cuda_core/multiGPUGradientAverage, cuda_core/numpyVsCupy, cuda_core/pageRank,
# cuda_core/parallelReduction, cuda_core/prefixSum, cuda_core/processCheckpoint, cuda_core/reductionMultiBlockCG,
# cuda_core/parallelReduction, cuda_core/prefixSum, cuda_core/reductionMultiBlockCG,
# cuda_core/simplePrint, cuda_core/tmaTensorMap:
# This test is not currently run in any CI job
@pytest.mark.parallel_threads_limit(1)
@pytest.mark.parametrize("sample_key", _SAMPLES)
@pytest.mark.parametrize("sample_key", _SUITE.keys)
@pytest.mark.samples
@pytest.mark.agent_authored(model="gpt-5")
def test_sample(sample_key: str) -> None:
if _GPU_COUNT == 0:
pytest.skip("No CUDA GPU detected on the test runner")

entry = _ENTRIES.get(sample_key)
if entry is None or not entry.is_file():
pytest.fail(f"Sample entrypoint missing: {sample_key}")

plan = build_run_plan(entry, _CONFIG, _GPU_COUNT, sample_key=sample_key)
result = run_sample(plan)

if result.status == "WAIVED":
pytest.skip(result.detail or "sample waived")
if result.status == "PASS":
return

# Re-print captured output through stdout/stderr so pytest's failure
# capture surfaces it in the report.
sys.stdout.flush()
pytest.fail(f"sample {sample_key} returned status={result.status} (rc={result.return_code}): {result.detail}")
_SUITE.check(sample_key)

Check failure on line 28 in cuda_core/tests/example_tests/test_samples.py

View workflow job for this annotation

GitHub Actions / Test linux-64 / pathfinder+bindings13+core13+meta13 / py3.12, CTK13.5.0 (wheels; bindings PR), GPU rtx4090, wsl

test_sample[cuda_core/processCheckpoint] Failed: sample cuda_core/processCheckpoint returned status=FAIL (rc=1): return code 1
120 changes: 116 additions & 4 deletions cuda_python_test_helpers/cuda_python_test_helpers/sample_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
from pathlib import Path
from typing import Any

import pytest
from packaging.requirements import InvalidRequirement, Requirement
from packaging.utils import canonicalize_name
from packaging.version import InvalidVersion
Expand All @@ -35,6 +36,8 @@
DEFAULT_TIMEOUT = 300
EXIT_WAIVED = 77
WAIVER_EXIT_CODE_ENV = "CUDA_PYTHON_SAMPLE_WAIVER_EXIT_CODE"
# Prefix of the RunResult detail for a sample waived for unmet PEP 723 dependencies.
UNMET_DEPENDENCIES = "unmet package requirement(s):"
_print_lock = threading.Lock()


Expand Down Expand Up @@ -318,7 +321,62 @@ def _provided_extras(dist: importlib.metadata.Distribution) -> set[str]:
return {canonicalize_name(extra) for extra in (dist.metadata.get_all("Provides-Extra") or ())}


def _distribution_mismatches(requirement: Requirement, dist: importlib.metadata.Distribution) -> list[str]:
def _extra_requirements(dist: importlib.metadata.Distribution, extra: str) -> list[Requirement]:
"""Return the requirements that ``extra`` adds to ``dist``'s base requirements."""
requirements: list[Requirement] = []
for spec in dist.requires or ():
requirement = Requirement(spec)
marker = requirement.marker
if marker is not None and marker.evaluate({"extra": extra}) and not marker.evaluate({"extra": ""}):
requirements.append(requirement)
return requirements


def _requirement_without_marker(requirement: Requirement) -> str:
text = requirement.name
if requirement.extras:
text += f"[{','.join(sorted(requirement.extras))}]"
return text + str(requirement.specifier)


def _extra_mismatches(
name: str, dist: importlib.metadata.Distribution, extra: str, seen: set[tuple[str, str]]
) -> list[str]:
"""Check the installed distributions that ``extra`` of ``dist`` requires.

A distribution the extra requires but that is not installed is accepted:
conda packages and a local CUDA Toolkit provide many of these libraries
without pip metadata. An installed one must satisfy the requirement, so
that, for example, ``cuda-core[cu13]`` is unmet when cuda-bindings 12.x is
installed.
"""
key = (name, extra)
if key in seen:
return []
seen.add(key)

mismatches: list[str] = []
for requirement in _extra_requirements(dist, extra):
for provider in _distribution_providers(requirement):
try:
provider_dist = importlib.metadata.distribution(provider)
except importlib.metadata.PackageNotFoundError:
continue
for detail in _distribution_mismatches(requirement, provider_dist, provider, seen):
mismatches.append(
f"extra {extra} requires {_requirement_without_marker(requirement)} "
f"({provider} {provider_dist.version}: {detail})"
)
break

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor · Functional Correctness · Quick win

important: Check fallback providers before rejecting an extra requirement.

If an extra requires cupy-cuda13x>=14, installed metadata for cupy-cuda13x==13.0 causes this loop to stop even when the fallback cupy==14.0 satisfies the requirement. The top-level provider loop accepts that fallback, but the recursive loop incorrectly waives the sample.

Collect mismatches until all providers fail. Break only when a provider satisfies the requirement.

return mismatches


def _distribution_mismatches(
requirement: Requirement,
dist: importlib.metadata.Distribution,
name: str,
seen: set[tuple[str, str]] | None = None,
) -> list[str]:
mismatches: list[str] = []
if requirement.specifier:
try:
Expand All @@ -329,9 +387,15 @@ def _distribution_mismatches(requirement: Requirement, dist: importlib.metadata.
if not version_matches:
mismatches.append(f"version {dist.version} does not satisfy {requirement.specifier}")

missing_extras = {canonicalize_name(extra) for extra in requirement.extras} - _provided_extras(dist)
requested_extras = {canonicalize_name(extra) for extra in requirement.extras}
missing_extras = requested_extras - _provided_extras(dist)
if missing_extras:
mismatches.append(f"does not provide extra(s): {', '.join(sorted(missing_extras))}")

if seen is None:
seen = set()
for extra in sorted(requested_extras - missing_extras):
mismatches.extend(_extra_mismatches(canonicalize_name(name), dist, extra, seen))
Comment on lines +397 to +398
return mismatches


Expand Down Expand Up @@ -362,7 +426,7 @@ def missing_dependencies(example: Path) -> list[str]:
dist = importlib.metadata.distribution(provider)
except importlib.metadata.PackageNotFoundError:
continue
mismatches = _distribution_mismatches(requirement, dist)
mismatches = _distribution_mismatches(requirement, dist, provider)
if not mismatches:
break
installed.append(f"{provider} {dist.version}: {', '.join(mismatches)}")
Expand Down Expand Up @@ -485,7 +549,7 @@ def run_sample(plan: RunPlan) -> RunResult:
_safe_print(f" [ERROR] {name}: {reason}")
return RunResult(sample, "ERROR", -1, reason, plan.sample_key)
if missing:
reason = f"unmet package requirement(s): {'; '.join(missing)}"
reason = f"{UNMET_DEPENDENCIES} {'; '.join(missing)}"
_safe_print(f" [WAIVED] {name}: {reason}")
return RunResult(sample, "WAIVED", EXIT_WAIVED, reason, plan.sample_key)

Expand Down Expand Up @@ -528,6 +592,54 @@ def run_sample(plan: RunPlan) -> RunResult:
return RunResult(sample, "FAIL", proc.returncode, msg, plan.sample_key)


# ---------------------------------------------------------------------------
# Pytest integration
# ---------------------------------------------------------------------------


class SampleSuite:
"""The samples one package owns, resolved once at collection time."""

def __init__(self, samples_dir: Path, namespace: str, config_path: Path) -> None:
self.entries = collect_sample_entries(samples_dir, namespace)
self.keys = sorted(self.entries)
self.config = load_config(config_path)
# Resolve the GPU count once, so every parametrized test id reports the
# same skip reason.
if self.keys:
self.gpu_count = get_gpu_count()
else:
self.gpu_count = 0

def check(self, sample_key: str, *, fail_on_unmet_dependencies: bool = False) -> None:
"""Run one sample and turn its result into a pytest outcome.

A waived sample skips. With ``fail_on_unmet_dependencies``, a sample
waived because its PEP 723 dependencies are not installed fails instead.
"""
if self.gpu_count == 0:
pytest.skip("No CUDA GPU detected on the test runner")

entry = self.entries.get(sample_key)
if entry is None or not entry.is_file():
pytest.fail(f"Sample entrypoint missing: {sample_key}")

plan = build_run_plan(entry, self.config, self.gpu_count, sample_key=sample_key)
result = run_sample(plan)

if result.status == "WAIVED":
if fail_on_unmet_dependencies and result.detail.startswith(UNMET_DEPENDENCIES):
pytest.fail(f"sample dependencies are not satisfied: {result.detail}")
pytest.skip(result.detail or "sample waived")
if result.status == "PASS":
return

# run_sample printed the sample's output; flush it so pytest's failure
# capture surfaces it in the report.
sys.stdout.flush()
pytest.fail(f"sample {sample_key} returned status={result.status} (rc={result.return_code}): {result.detail}")


# ---------------------------------------------------------------------------
# Entry point
# ---------------------------------------------------------------------------
Expand Down
4 changes: 2 additions & 2 deletions samples/cuda_core/binarySearch/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ diverge on present values). Results are verified against
- CUDA Toolkit 13.0 or newer
- Python 3.11 or newer
- `cuda-cccl` (>=1.0.0)
- `cuda-core` (>=1.0.0)
- `cuda-core[cu13]` (>=1.0.0)
- `cupy-cuda13x` (>=14.0.0)

If the CUDA toolkit is not on your `PATH`, set `CUDA_HOME` so that
Expand All @@ -79,7 +79,7 @@ pip install -r requirements.txt
The `requirements.txt` installs:

- `cuda-cccl` (>=1.0.0) - ships the `cuda.compute` module
- `cuda-core` (>=1.0.0)
- `cuda-core[cu13]` (>=1.0.0)
- `cupy-cuda13x` (>=14.0.0)
- `numpy` (>=1.24.0)

Expand Down
2 changes: 1 addition & 1 deletion samples/cuda_core/binarySearch/binarySearch.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

# /// script
# dependencies = ["cuda-cccl[cu13]>=1.0.0", "cuda-core>=1.0.0", "cupy-cuda13x>=14.0.0", "numpy>=1.24.0"]
# dependencies = ["cuda-cccl[cu13]>=1.0.0", "cuda-core[cu13]>=1.0.0", "cupy-cuda13x>=14.0.0", "numpy>=1.24.0"]
# ///

"""
Expand Down
2 changes: 1 addition & 1 deletion samples/cuda_core/binarySearch/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
cuda-cccl[cu13]>=1.0.0
cuda-core>=1.0.0
cuda-core[cu13]>=1.0.0
cupy-cuda13x>=14.0.0
numpy>=1.24.0
2 changes: 1 addition & 1 deletion samples/cuda_core/blockwiseSum/blockwiseSum.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

# /// script
# dependencies = ["cuda-python>=13.0.0", "cuda-core>=1.0.0", "cupy-cuda13x>=14.0.0", "numpy>=2.3.2"]
# dependencies = ["cuda-core[cu13]>=1.0.0", "cupy-cuda13x>=14.0.0", "numpy>=2.3.2"]
# ///

"""
Expand Down
3 changes: 1 addition & 2 deletions samples/cuda_core/blockwiseSum/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
# Block-wise Array Sum Requirements

cuda-python>=13.0.0
cuda-core>=1.0.0
cuda-core[cu13]>=1.0.0
cupy-cuda13x>=14.0.0
numpy>=2.3.2
3 changes: 1 addition & 2 deletions samples/cuda_core/blurImageUnifiedMemory/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -105,8 +105,7 @@ When returning a zero-copy view, the caller must close the buffers after use (e.

- CUDA Toolkit 13.0 or newer
- Python 3.11 or newer
- `cuda-python` package (13.0.0+)
- `cuda-core` package (>=1.0.0)
- `cuda-core[cu13]` package (>=1.0.0)
- `numpy` package (>=2.3.2)
- `pillow` package (10.0.0+)

Expand Down
Loading
Loading