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
3 changes: 3 additions & 0 deletions cuda_pathfinder/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@ Windows.
- **Load orchestration**:
- `load_nvidia_dynamic_lib.py` coordinates find/load phases, dependency
loading, driver-lib fast path, and cache semantics.
- **Static and bitcode libraries**:
- `_static_libs/locate_file.py` holds the one search that
`find_static_lib.py` and `find_bitcode_lib.py` share.
- **Process isolation helper**:
- `cuda/pathfinder/_utils/spawned_process_runner.py` is used where process
global dynamic loader state would otherwise leak across tests.
Expand Down
120 changes: 16 additions & 104 deletions cuda_pathfinder/cuda/pathfinder/_static_libs/find_bitcode_lib.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,12 @@
# SPDX-License-Identifier: Apache-2.0

import functools
import os
from dataclasses import dataclass
from pathlib import Path
from typing import NoReturn, TypedDict
from typing import TypedDict

from cuda.pathfinder._utils.env_vars import get_cuda_path_or_home
from cuda.pathfinder._utils.find_sub_dirs import find_sub_dirs_all_sitepackages
from cuda.pathfinder._static_libs.locate_file import locate_file
from cuda.pathfinder._utils.platform_aware import IS_WINDOWS

from .._utils.resolve_path import resolve_path


class BitcodeLibNotFoundError(RuntimeError):
"""Raised when a bitcode library cannot be found."""
Expand Down Expand Up @@ -69,110 +64,27 @@ class _BitcodeLibInfo(TypedDict):
)


def _no_such_file_in_dir(directory: Path, filename: str, error_messages: list[str], attachments: list[str]) -> None:
error_messages.append(f"No such file: {directory / filename}")
if directory.is_dir():
attachments.append(f' listdir("{directory}"):')
for node in sorted(node_path.name for node_path in directory.iterdir()):
attachments.append(f" {node}")
else:
attachments.append(f' Directory does not exist: "{directory}"')


class _FindBitcodeLib:
def __init__(self, name: str) -> None:
if name not in _SUPPORTED_BITCODE_LIBS_INFO: # Updated reference
raise ValueError(f"Unknown bitcode library: '{name}'. Supported: {', '.join(SUPPORTED_BITCODE_LIBS)}")
self.name: str = name
self.config: _BitcodeLibInfo = _SUPPORTED_BITCODE_LIBS_INFO[name] # Updated reference
self.filename: str = self.config["filename"]
self.rel_path: str = self.config["rel_path"]
self.site_packages_dirs: tuple[str, ...] = self.config["site_packages_dirs"]
self.error_messages: list[str] = []
self.attachments: list[str] = []

def try_site_packages(self) -> Path | None:
for rel_dir in self.site_packages_dirs:
sub_dir = tuple(rel_dir.split("/"))
for abs_dir in find_sub_dirs_all_sitepackages(sub_dir):
file_path = Path(abs_dir, self.filename)
if file_path.is_file():
return resolve_path(file_path)
return None

def try_with_conda_prefix(self) -> Path | None:
conda_prefix = os.environ.get("CONDA_PREFIX")
if not conda_prefix:
return None

anchor = Path(conda_prefix, "Library") if IS_WINDOWS else Path(conda_prefix)
file_path = anchor / self.rel_path / self.filename
if file_path.is_file():
return resolve_path(file_path)
return None

def try_with_cuda_home(self) -> Path | None:
cuda_home = get_cuda_path_or_home()
if cuda_home is None:
self.error_messages.append("CUDA_HOME/CUDA_PATH not set")
return None

anchor = Path(cuda_home)
file_path = anchor / self.rel_path / self.filename
if file_path.is_file():
return resolve_path(file_path)

_no_such_file_in_dir(
anchor / self.rel_path,
self.filename,
self.error_messages,
self.attachments,
)
return None

def raise_not_found_error(self) -> NoReturn:
err = ", ".join(self.error_messages) if self.error_messages else "No search paths available"
att = "\n".join(self.attachments) if self.attachments else ""
raise BitcodeLibNotFoundError(f'Failure finding "{self.filename}": {err}\n{att}')


def locate_bitcode_lib(name: str) -> LocatedBitcodeLib:
"""Locate a bitcode library by name, returning its resolved absolute path.

Raises:
ValueError: If ``name`` is not a supported bitcode library.
BitcodeLibNotFoundError: If the bitcode library cannot be found.
"""
finder = _FindBitcodeLib(name)

abs_path = finder.try_site_packages()
if abs_path is not None:
return LocatedBitcodeLib(
name=name,
abs_path=str(abs_path),
filename=finder.filename,
found_via="site-packages",
)

abs_path = finder.try_with_conda_prefix()
if abs_path is not None:
return LocatedBitcodeLib(
name=name,
abs_path=str(abs_path),
filename=finder.filename,
found_via="conda",
)

abs_path = finder.try_with_cuda_home()
if abs_path is not None:
return LocatedBitcodeLib(
name=name,
abs_path=str(abs_path),
filename=finder.filename,
found_via="CUDA_PATH",
)

finder.raise_not_found_error()
if name not in _SUPPORTED_BITCODE_LIBS_INFO:
raise ValueError(f"Unknown bitcode library: '{name}'. Supported: {', '.join(SUPPORTED_BITCODE_LIBS)}")
info = _SUPPORTED_BITCODE_LIBS_INFO[name]
filename = info["filename"]
rel_paths = (info["rel_path"],)

abs_path, found_via = locate_file(
filename,
site_packages_dirs=info["site_packages_dirs"],
conda_rel_paths=rel_paths,
ctk_rel_paths=rel_paths,
not_found_error=BitcodeLibNotFoundError,
)
return LocatedBitcodeLib(name=name, abs_path=abs_path, filename=filename, found_via=found_via)


@functools.cache
Expand Down
121 changes: 15 additions & 106 deletions cuda_pathfinder/cuda/pathfinder/_static_libs/find_static_lib.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,14 @@
# SPDX-License-Identifier: Apache-2.0

import functools
import os
from dataclasses import dataclass
from pathlib import Path
from typing import NoReturn, TypedDict
from typing import TypedDict

from cuda.pathfinder._utils.env_vars import get_cuda_path_or_home
from cuda.pathfinder._utils.find_sub_dirs import find_sub_dirs_all_sitepackages
from cuda.pathfinder._static_libs.locate_file import locate_file
from cuda.pathfinder._utils.platform_aware import IS_WINDOWS
from cuda.pathfinder._utils.windows_arch import windows_python_arch

from .._utils.resolve_path import resolve_path


class StaticLibNotFoundError(RuntimeError):
"""Raised when a static library cannot be found."""
Expand Down Expand Up @@ -65,113 +61,26 @@ def _cudadevrt_info() -> _StaticLibInfo:
SUPPORTED_STATIC_LIBS: tuple[str, ...] = tuple(sorted(_SUPPORTED_STATIC_LIBS_INFO.keys()))


def _no_such_file_in_dir(directory: Path, filename: str, error_messages: list[str], attachments: list[str]) -> None:
error_messages.append(f"No such file: {directory / filename}")
if directory.is_dir():
attachments.append(f' listdir("{directory}"):')
for node in sorted(node_path.name for node_path in directory.iterdir()):
attachments.append(f" {node}")
else:
attachments.append(f' Directory does not exist: "{directory}"')


class _FindStaticLib:
def __init__(self, name: str) -> None:
if name not in _SUPPORTED_STATIC_LIBS_INFO:
raise ValueError(f"Unknown static library: '{name}'. Supported: {', '.join(SUPPORTED_STATIC_LIBS)}")
self.name: str = name
self.config: _StaticLibInfo = _SUPPORTED_STATIC_LIBS_INFO[name]
self.filename: str = self.config["filename"]
self.ctk_rel_paths: tuple[str, ...] = self.config["ctk_rel_paths"]
self.conda_rel_paths: tuple[str, ...] = self.config["conda_rel_paths"]
self.site_packages_dirs: tuple[str, ...] = self.config["site_packages_dirs"]
self.error_messages: list[str] = []
self.attachments: list[str] = []

def try_site_packages(self) -> Path | None:
for rel_dir in self.site_packages_dirs:
sub_dir = tuple(rel_dir.split("/"))
for abs_dir in find_sub_dirs_all_sitepackages(sub_dir):
file_path = Path(abs_dir, self.filename)
if file_path.is_file():
return resolve_path(file_path)
return None

def try_with_conda_prefix(self) -> Path | None:
conda_prefix = os.environ.get("CONDA_PREFIX")
if not conda_prefix:
return None

anchor = Path(conda_prefix, "Library") if IS_WINDOWS else Path(conda_prefix)
for rel_path in self.conda_rel_paths:
file_path = anchor / rel_path / self.filename
if file_path.is_file():
return resolve_path(file_path)
return None

def try_with_cuda_home(self) -> Path | None:
cuda_home = get_cuda_path_or_home()
if cuda_home is None:
self.error_messages.append("CUDA_HOME/CUDA_PATH not set")
return None

anchor = Path(cuda_home)
for rel_path in self.ctk_rel_paths:
file_path = anchor / rel_path / self.filename
if file_path.is_file():
return resolve_path(file_path)

_no_such_file_in_dir(
anchor / self.ctk_rel_paths[0],
self.filename,
self.error_messages,
self.attachments,
)
return None

def raise_not_found_error(self) -> NoReturn:
err = ", ".join(self.error_messages) if self.error_messages else "No search paths available"
att = "\n".join(self.attachments) if self.attachments else ""
raise StaticLibNotFoundError(f'Failure finding "{self.filename}": {err}\n{att}')


def locate_static_lib(name: str) -> LocatedStaticLib:
"""Locate a static library by name, returning its resolved absolute path.

Raises:
ValueError: If ``name`` is not a supported static library.
StaticLibNotFoundError: If the static library cannot be found.
"""
finder = _FindStaticLib(name)

abs_path = finder.try_site_packages()
if abs_path is not None:
return LocatedStaticLib(
name=name,
abs_path=str(abs_path),
filename=finder.filename,
found_via="site-packages",
)

abs_path = finder.try_with_conda_prefix()
if abs_path is not None:
return LocatedStaticLib(
name=name,
abs_path=str(abs_path),
filename=finder.filename,
found_via="conda",
)

abs_path = finder.try_with_cuda_home()
if abs_path is not None:
return LocatedStaticLib(
name=name,
abs_path=str(abs_path),
filename=finder.filename,
found_via="CUDA_PATH",
)

finder.raise_not_found_error()
if name not in _SUPPORTED_STATIC_LIBS_INFO:
raise ValueError(f"Unknown static library: '{name}'. Supported: {', '.join(SUPPORTED_STATIC_LIBS)}")
info = _SUPPORTED_STATIC_LIBS_INFO[name]
filename = info["filename"]

abs_path, found_via = locate_file(
filename,
site_packages_dirs=info["site_packages_dirs"],
conda_rel_paths=info["conda_rel_paths"],
ctk_rel_paths=info["ctk_rel_paths"],
not_found_error=StaticLibNotFoundError,
)
return LocatedStaticLib(name=name, abs_path=abs_path, filename=filename, found_via=found_via)


@functools.cache
Expand Down
75 changes: 75 additions & 0 deletions cuda_pathfinder/cuda/pathfinder/_static_libs/locate_file.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

"""Search shared by the static-library and bitcode-library finders."""

import os
from pathlib import Path

from cuda.pathfinder._utils.env_vars import get_cuda_path_or_home
from cuda.pathfinder._utils.find_sub_dirs import find_sub_dirs_all_sitepackages
from cuda.pathfinder._utils.platform_aware import IS_WINDOWS

from .._utils.resolve_path import resolve_path


def _resolved_if_file(directory: Path | str, filename: str) -> str | None:
file_path = Path(directory, filename)
if file_path.is_file():
return str(resolve_path(file_path))
return None


def locate_file(
filename: str,
*,
site_packages_dirs: tuple[str, ...],
conda_rel_paths: tuple[str, ...],
ctk_rel_paths: tuple[str, ...],
not_found_error: type[Exception],
) -> tuple[str, str]:
"""Return ``(abs_path, found_via)`` for the first place that has *filename*.

Search order: NVIDIA wheels (``site-packages``), ``$CONDA_PREFIX``, then
``$CUDA_PATH`` / ``$CUDA_HOME``. Directories are tried first-to-last.

Raises:
not_found_error: If no place has *filename*. The message describes the
``CUDA_PATH`` root that this search read.
"""
for rel_dir in site_packages_dirs:
for abs_dir in find_sub_dirs_all_sitepackages(tuple(rel_dir.split("/"))):
abs_path = _resolved_if_file(abs_dir, filename)
if abs_path is not None:
return abs_path, "site-packages"

conda_prefix = os.environ.get("CONDA_PREFIX")
if conda_prefix:
anchor = Path(conda_prefix, "Library") if IS_WINDOWS else Path(conda_prefix)
for rel_path in conda_rel_paths:
abs_path = _resolved_if_file(anchor / rel_path, filename)
if abs_path is not None:
return abs_path, "conda"

cuda_home = get_cuda_path_or_home()
if cuda_home is not None:
for rel_path in ctk_rel_paths:
abs_path = _resolved_if_file(Path(cuda_home, rel_path), filename)
if abs_path is not None:
return abs_path, "CUDA_PATH"

raise not_found_error(_not_found_message(filename, cuda_home, ctk_rel_paths))


def _not_found_message(filename: str, cuda_home: str | None, ctk_rel_paths: tuple[str, ...]) -> str:
"""Explain a miss by describing the first directory tried under *cuda_home*."""
if cuda_home is None:
return f'Failure finding "{filename}": CUDA_HOME/CUDA_PATH not set\n'

directory = Path(cuda_home, ctk_rel_paths[0])
if directory.is_dir():
listing = [f' listdir("{directory}"):']
listing.extend(f" {node}" for node in sorted(node_path.name for node_path in directory.iterdir()))
else:
listing = [f' Directory does not exist: "{directory}"']
return f'Failure finding "{filename}": No such file: {directory / filename}\n' + "\n".join(listing)
Loading
Loading