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
93 changes: 76 additions & 17 deletions cuda_pathfinder/cuda/pathfinder/_static_libs/find_bitcode_lib.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

import functools
import os
import re
from dataclasses import dataclass
from pathlib import Path
from typing import NoReturn, TypedDict
Expand All @@ -29,17 +30,26 @@ class LocatedBitcodeLib:


class _BitcodeLibInfo(TypedDict):
"""Bitcode-library metadata with ordered alternatives searched first-to-last."""
"""Bitcode-library metadata with ordered alternatives searched first-to-last.

filename: str
File paths are relative to the library directory. ``rel_path`` selects
that directory for Conda and CUDA installations, and
``site_packages_dirs`` does so for site-packages.

``{sm_arch}`` expands to the caller's value, such as ``90`` or ``100a``.
"""

# Keys: None for the default file, "*" for unlisted SMs, or an SM like "100a".
# Values: relative paths. Entries used with an SM may contain {sm_arch}.
filenames: dict[str | None, str]
rel_path: str
site_packages_dirs: tuple[str, ...]
available_on_windows: bool


_SUPPORTED_BITCODE_LIBS_INFO: dict[str, _BitcodeLibInfo] = {
"device": {
"filename": "libdevice.10.bc",
"filenames": {None: "libdevice.10.bc"},
"rel_path": "nvvm/libdevice",
"site_packages_dirs": (
"nvidia/cu13/nvvm/libdevice",
Expand All @@ -48,13 +58,19 @@ class _BitcodeLibInfo(TypedDict):
"available_on_windows": True,
},
"nccl_device": {
"filename": "libnccl_device.bc",
"filenames": {
None: "libnccl_device.bc",
"*": "libnccl_device_sm_{sm_arch}.bc",
},
"rel_path": "lib",
"site_packages_dirs": ("nvidia/nccl/lib",),
"available_on_windows": False,
},
"nvshmem_device": {
"filename": "libnvshmem_device.bc",
"filenames": {
None: "libnvshmem_device.bc",
"*": "libnvshmem_device_sm_{sm_arch}.bc",
},
"rel_path": "lib",
"site_packages_dirs": ("nvidia/nvshmem/lib",),
"available_on_windows": False,
Expand All @@ -80,12 +96,28 @@ def _no_such_file_in_dir(directory: Path, filename: str, error_messages: list[st


class _FindBitcodeLib:
def __init__(self, name: str) -> None:
def __init__(self, name: str, sm_arch: str | None) -> 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.sm_arch: str | None = sm_arch
self.config: _BitcodeLibInfo = _SUPPORTED_BITCODE_LIBS_INFO[name] # Updated reference
self.filename: str = self.config["filename"]
filenames = self.config["filenames"]
if sm_arch is None:
filename = filenames.get(None)
if filename is None:
raise BitcodeLibNotFoundError(f"Bitcode library {name!r} has no default file configured")
else:
if not isinstance(sm_arch, str) or re.fullmatch(r"[0-9]+[a-z]?", sm_arch) is None:
raise ValueError("sm_arch must be a string such as '90' or '100a' without the 'sm_' prefix, or None")
template = filenames.get(sm_arch, filenames.get("*"))
if template is None:
raise BitcodeLibNotFoundError(
f"Bitcode library {name!r} has no file configured for sm_arch={sm_arch!r}"
)
filename = template.format(sm_arch=sm_arch)

self.filename: str = 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] = []
Expand Down Expand Up @@ -123,8 +155,8 @@ def try_with_cuda_home(self) -> Path | None:
return resolve_path(file_path)

_no_such_file_in_dir(
anchor / self.rel_path,
self.filename,
file_path.parent,
file_path.name,
self.error_messages,
self.attachments,
)
Expand All @@ -133,24 +165,38 @@ def try_with_cuda_home(self) -> Path | 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}')
target = f'"{self.filename}"'
if self.sm_arch is not None:
target += f" for {self.name!r} with sm_arch={self.sm_arch!r}"
raise BitcodeLibNotFoundError(f"Failure finding {target}: {err}\n{att}")


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

Args:
name: Supported bitcode library name.
sm_arch: Target SM without the ``sm_`` prefix, such as ``"90"`` or
``"100a"``. If specified, search only for the file selected for
that SM by the library's configuration. The matching file must
be present in the installation.
Pass ``None`` or omit this argument to search for the default file.

Raises:
ValueError: If ``name`` is not a supported bitcode library.
Also raised if ``sm_arch`` is invalid.
BitcodeLibNotFoundError: If the bitcode library cannot be found.
Also raised if no file is configured for the request.
"""
finder = _FindBitcodeLib(name)
finder = _FindBitcodeLib(name, sm_arch)
filename = Path(finder.filename).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,
filename=filename,
found_via="site-packages",
)

Expand All @@ -159,7 +205,7 @@ def locate_bitcode_lib(name: str) -> LocatedBitcodeLib:
return LocatedBitcodeLib(
name=name,
abs_path=str(abs_path),
filename=finder.filename,
filename=filename,
found_via="conda",
)

Expand All @@ -168,19 +214,32 @@ def locate_bitcode_lib(name: str) -> LocatedBitcodeLib:
return LocatedBitcodeLib(
name=name,
abs_path=str(abs_path),
filename=finder.filename,
filename=filename,
found_via="CUDA_PATH",
)

finder.raise_not_found_error()


@functools.cache
def find_bitcode_lib(name: str) -> str:
def find_bitcode_lib(name: str, *, sm_arch: str | None = None) -> str:
"""Find the resolved absolute path to a bitcode library.

Args:
name: Supported bitcode library name.
sm_arch: Target SM without the ``sm_`` prefix, such as ``"90"``. See
:func:`locate_bitcode_lib` for file selection.

Raises:
ValueError: If ``name`` is not a supported bitcode library.
Also raised if the ``sm_arch`` string has an invalid format.
BitcodeLibNotFoundError: If the bitcode library cannot be found.
Also raised if no file is configured for the request.

Example:
Find ``libnvshmem_device_sm_100.bc`` if installed.

>>> from cuda.pathfinder import find_bitcode_lib
>>> path = find_bitcode_lib("nvshmem_device", sm_arch="100")
"""
return locate_bitcode_lib(name).abs_path
return locate_bitcode_lib(name, sm_arch=sm_arch).abs_path
94 changes: 83 additions & 11 deletions cuda_pathfinder/tests/test_find_bitcode_lib.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ def _bitcode_lib_info(libname: str):


def _bitcode_lib_filename(libname: str) -> str:
return _bitcode_lib_info(libname)["filename"]
return _bitcode_lib_info(libname)["filenames"][None]


@pytest.fixture
Expand All @@ -36,9 +36,8 @@ def clear_find_bitcode_lib_cache():
get_cuda_path_or_home.cache_clear()


def _make_bitcode_lib_file(dir_path: Path, libname: str) -> str:
dir_path.mkdir(parents=True, exist_ok=True)
file_path = dir_path / _bitcode_lib_filename(libname)
def _make_bitcode_lib_file(file_path: Path) -> str:
file_path.parent.mkdir(parents=True, exist_ok=True)
file_path.touch()
return str(file_path)

Expand Down Expand Up @@ -91,14 +90,15 @@ def test_locate_bitcode_lib(info_summary_append, libname):
@pytest.mark.usefixtures("clear_find_bitcode_lib_cache")
@pytest.mark.parametrize("libname", SUPPORTED_BITCODE_LIBS)
def test_locate_bitcode_lib_search_order(monkeypatch, tmp_path, libname):
filename = _bitcode_lib_filename(libname)
site_packages_lib_dir = _site_packages_bitcode_lib_dir_under(tmp_path / "site-packages", libname)
site_packages_path = _make_bitcode_lib_file(site_packages_lib_dir, libname)
site_packages_path = _make_bitcode_lib_file(site_packages_lib_dir / filename)

conda_prefix = tmp_path / "conda-prefix"
conda_path = _make_bitcode_lib_file(_bitcode_lib_dir_under(_conda_anchor(conda_prefix), libname), libname)
conda_path = _make_bitcode_lib_file(_bitcode_lib_dir_under(_conda_anchor(conda_prefix), libname) / filename)

cuda_home = tmp_path / "cuda-home"
cuda_home_path = _make_bitcode_lib_file(_bitcode_lib_dir_under(cuda_home, libname), libname)
cuda_home_path = _make_bitcode_lib_file(_bitcode_lib_dir_under(cuda_home, libname) / filename)

site_packages_sub_dirs = tuple(
tuple(rel_dir.split("/")) for rel_dir in _bitcode_lib_info(libname)["site_packages_dirs"]
Expand Down Expand Up @@ -157,7 +157,7 @@ def test_locate_bitcode_lib_returns_resolved_path_for_relative_root(monkeypatch,
monkeypatch.setenv("CUDA_HOME", str(root))
lib_dir = root / Path(info["rel_path"])

expected = (tmp_path / lib_dir / info["filename"]).resolve()
expected = (tmp_path / lib_dir / _bitcode_lib_filename("device")).resolve()
expected.parent.mkdir(parents=True)
expected.touch()
located = locate_bitcode_lib("device")
Expand All @@ -184,7 +184,7 @@ def test_locate_bitcode_lib_preserves_symlink_parent(monkeypatch, tmp_path):
(real_root / "child").mkdir(parents=True)
(tmp_path / "alias").symlink_to(real_root / "child", target_is_directory=True)
info = _bitcode_lib_info("device")
expected = real_root / info["rel_path"] / info["filename"]
expected = real_root / info["rel_path"] / _bitcode_lib_filename("device")
expected.parent.mkdir(parents=True)
expected.touch()

Expand All @@ -208,13 +208,14 @@ def test_locate_bitcode_lib_resolves_symlinked_file(monkeypatch, tmp_path):
info = _bitcode_lib_info("device")
target = tmp_path / "actual-library"
target.touch()
candidate = root / info["rel_path"] / info["filename"]
filename = _bitcode_lib_filename("device")
candidate = root / info["rel_path"] / filename
candidate.parent.mkdir(parents=True)
candidate.symlink_to(target)

located = locate_bitcode_lib("device")
assert located.abs_path == str(target.resolve())
assert located.filename == info["filename"]
assert located.filename == filename
assert find_bitcode_lib("device") == located.abs_path


Expand Down Expand Up @@ -266,3 +267,74 @@ def test_find_bitcode_lib_not_found_error_without_cuda_home(monkeypatch):
def test_find_bitcode_lib_invalid_name():
with pytest.raises(ValueError, match="Unknown bitcode library"):
find_bitcode_lib_module.locate_bitcode_lib("invalid")


@pytest.fixture
def sm_bitcode_layout(monkeypatch, tmp_path):
site_packages = tmp_path / "site-packages"
cuda_home = tmp_path / "cuda-home"
monkeypatch.setattr(
find_bitcode_lib_module,
"find_sub_dirs_all_sitepackages",
lambda sub_dir: [str(site_packages.joinpath(*sub_dir))],
)
monkeypatch.delenv("CONDA_PREFIX", raising=False)
monkeypatch.setenv("CUDA_HOME", str(cuda_home))
monkeypatch.delenv("CUDA_PATH", raising=False)
return site_packages, cuda_home


@pytest.mark.usefixtures("clear_find_bitcode_lib_cache")
@pytest.mark.parametrize(
"libname", [name for name in SUPPORTED_BITCODE_LIBS if name in ("nccl_device", "nvshmem_device")]
)
def test_sm_arch_selection_and_cache(sm_bitcode_layout, libname):
site_packages, _ = sm_bitcode_layout
site_dir = _site_packages_bitcode_lib_dir_under(site_packages, libname)
future_sm = _make_bitcode_lib_file(site_dir / f"lib{libname}_sm_999a.bc")
sm100 = _make_bitcode_lib_file(site_dir / f"lib{libname}_sm_100.bc")
default = _make_bitcode_lib_file(site_dir / _bitcode_lib_filename(libname))

assert find_bitcode_lib(libname, sm_arch="999a") == future_sm
assert find_bitcode_lib(libname, sm_arch="100") == sm100
assert find_bitcode_lib(libname) == default


@pytest.mark.usefixtures("clear_find_bitcode_lib_cache")
@pytest.mark.parametrize("libname", SUPPORTED_BITCODE_LIBS)
def test_sm_arch_does_not_use_default_file(sm_bitcode_layout, libname):
site_packages, _ = sm_bitcode_layout
site_dir = _site_packages_bitcode_lib_dir_under(site_packages, libname)
default = _make_bitcode_lib_file(site_dir / _bitcode_lib_filename(libname))
assert find_bitcode_lib(libname, sm_arch=None) == default
with pytest.raises(BitcodeLibNotFoundError, match="sm_arch='100'"):
find_bitcode_lib(libname, sm_arch="100")


@pytest.mark.usefixtures("clear_find_bitcode_lib_cache")
def test_exact_sm_path_takes_precedence_over_wildcard(monkeypatch, sm_bitcode_layout):
site_packages, cuda_home = sm_bitcode_layout
site_dir = _site_packages_bitcode_lib_dir_under(site_packages, "device")
config = dict(_bitcode_lib_info("device"))
config["filenames"] = {"100a": "{sm_arch}/device.bc", "*": "generic.bc"}
monkeypatch.setitem(find_bitcode_lib_module._SUPPORTED_BITCODE_LIBS_INFO, "device", config)
generic = _make_bitcode_lib_file(site_dir / "generic.bc")
exact_dir = _bitcode_lib_dir_under(cuda_home, "device") / "100a"
exact = _make_bitcode_lib_file(exact_dir / "device.bc")

located = locate_bitcode_lib("device", sm_arch="100a")
assert located.abs_path == exact
assert located.filename == "device.bc"
assert locate_bitcode_lib("device", sm_arch="100").abs_path == generic
Path(exact).unlink()
with pytest.raises(BitcodeLibNotFoundError, match=r"100a/device\.bc") as exc_info:
locate_bitcode_lib("device", sm_arch="100a")
assert f'listdir("{exact_dir}"):' in str(exc_info.value)
with pytest.raises(BitcodeLibNotFoundError, match="no default file configured"):
locate_bitcode_lib("device")


@pytest.mark.parametrize("sm_arch", ["", 100, "sm_100", "*", "100/../90", r"100\..\90"])
def test_invalid_sm_arch(sm_arch):
with pytest.raises(ValueError, match="sm_arch must be a string"):
locate_bitcode_lib("device", sm_arch=sm_arch)
Loading