Coverage for cuda/pathfinder/_static_libs/find_bitcode_lib.py: 100.00%
80 statements
« prev ^ index » next coverage.py v7.18.0, created at 2026-12-03 01:06 +0000
« prev ^ index » next coverage.py v7.18.0, created at 2026-12-03 01:06 +0000
1# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2# SPDX-License-Identifier: Apache-2.0
4import functools
5import os
6from dataclasses import dataclass
7from pathlib import Path
8from typing import NoReturn, TypedDict
10from cuda.pathfinder._utils.env_vars import get_cuda_path_or_home
11from cuda.pathfinder._utils.find_sub_dirs import find_sub_dirs_all_sitepackages
12from cuda.pathfinder._utils.platform_aware import IS_WINDOWS
14from .._utils.resolve_path import resolve_path
17class BitcodeLibNotFoundError(RuntimeError):
18 """Raised when a bitcode library cannot be found."""
21@dataclass(frozen=True)
22class LocatedBitcodeLib:
23 """Information about a located bitcode library."""
25 name: str
26 abs_path: str
27 filename: str
28 found_via: str
31class _BitcodeLibInfo(TypedDict):
32 """Bitcode-library metadata with ordered alternatives searched first-to-last."""
34 filename: str
35 rel_path: str
36 site_packages_dirs: tuple[str, ...]
37 available_on_windows: bool
40_SUPPORTED_BITCODE_LIBS_INFO: dict[str, _BitcodeLibInfo] = {
41 "device": {
42 "filename": "libdevice.10.bc",
43 "rel_path": "nvvm/libdevice",
44 "site_packages_dirs": (
45 "nvidia/cu13/nvvm/libdevice",
46 "nvidia/cuda_nvcc/nvvm/libdevice",
47 ),
48 "available_on_windows": True,
49 },
50 "nccl_device": {
51 "filename": "libnccl_device.bc",
52 "rel_path": "lib",
53 "site_packages_dirs": ("nvidia/nccl/lib",),
54 "available_on_windows": False,
55 },
56 "nvshmem_device": {
57 "filename": "libnvshmem_device.bc",
58 "rel_path": "lib",
59 "site_packages_dirs": ("nvidia/nvshmem/lib",),
60 "available_on_windows": False,
61 },
62}
64# Public API: just the supported library names
65SUPPORTED_BITCODE_LIBS: tuple[str, ...] = tuple(
66 sorted(
67 name for name, info in _SUPPORTED_BITCODE_LIBS_INFO.items() if not IS_WINDOWS or info["available_on_windows"]
68 )
69)
72def _no_such_file_in_dir(directory: Path, filename: str, error_messages: list[str], attachments: list[str]) -> None:
73 error_messages.append(f"No such file: {directory / filename}") 1afge
74 if directory.is_dir(): 1afge
75 attachments.append(f' listdir("{directory}"):') 1a
76 for node in sorted(node_path.name for node_path in directory.iterdir()): 1a
77 attachments.append(f" {node}") 1a
78 else:
79 attachments.append(f' Directory does not exist: "{directory}"') 1fge
82class _FindBitcodeLib:
83 def __init__(self, name: str) -> None:
84 if name not in _SUPPORTED_BITCODE_LIBS_INFO: # Updated reference 1pahifgjklnobcde
85 raise ValueError(f"Unknown bitcode library: '{name}'. Supported: {', '.join(SUPPORTED_BITCODE_LIBS)}") 1p
86 self.name: str = name 1ahifgjklnobcde
87 self.config: _BitcodeLibInfo = _SUPPORTED_BITCODE_LIBS_INFO[name] # Updated reference 1ahifgjklnobcde
88 self.filename: str = self.config["filename"] 1ahifgjklnobcde
89 self.rel_path: str = self.config["rel_path"] 1ahifgjklnobcde
90 self.site_packages_dirs: tuple[str, ...] = self.config["site_packages_dirs"] 1ahifgjklnobcde
91 self.error_messages: list[str] = [] 1ahifgjklnobcde
92 self.attachments: list[str] = [] 1ahifgjklnobcde
94 def try_site_packages(self) -> Path | None:
95 for rel_dir in self.site_packages_dirs: 1ahifgjklnobcde
96 sub_dir = tuple(rel_dir.split("/")) 1ahifgjklnobcde
97 for abs_dir in find_sub_dirs_all_sitepackages(sub_dir): 1ahifgjklnobcde
98 file_path = Path(abs_dir, self.filename) 1obcd
99 if file_path.is_file(): 1obcd
100 return resolve_path(file_path) 1obcd
101 return None 1ahifgjklnbcde
103 def try_with_conda_prefix(self) -> Path | None:
104 conda_prefix = os.environ.get("CONDA_PREFIX") 1ahifgjklnbcde
105 if not conda_prefix: 1ahifgjklnbcde
106 return None 1ahifgjkle
108 anchor = Path(conda_prefix, "Library") if IS_WINDOWS else Path(conda_prefix) 1nbcd
109 file_path = anchor / self.rel_path / self.filename 1nbcd
110 if file_path.is_file(): 1nbcd
111 return resolve_path(file_path) 1nbcd
112 return None 1bcd
114 def try_with_cuda_home(self) -> Path | None:
115 cuda_home = get_cuda_path_or_home() 1ahifgjklbcde
116 if cuda_home is None: 1ahifgjklbcde
117 self.error_messages.append("CUDA_HOME/CUDA_PATH not set") 1h
118 return None 1h
120 anchor = Path(cuda_home) 1aifgjklbcde
121 file_path = anchor / self.rel_path / self.filename 1aifgjklbcde
122 if file_path.is_file(): 1aifgjklbcde
123 return resolve_path(file_path) 1ijklbcd
125 _no_such_file_in_dir( 1afge
126 anchor / self.rel_path,
127 self.filename,
128 self.error_messages,
129 self.attachments,
130 )
131 return None 1afge
133 def raise_not_found_error(self) -> NoReturn:
134 err = ", ".join(self.error_messages) if self.error_messages else "No search paths available" 1ahfge
135 att = "\n".join(self.attachments) if self.attachments else "" 1ahfge
136 raise BitcodeLibNotFoundError(f'Failure finding "{self.filename}": {err}\n{att}') 1ahfge
139def locate_bitcode_lib(name: str) -> LocatedBitcodeLib:
140 """Locate a bitcode library by name, returning its resolved absolute path.
142 Raises:
143 ValueError: If ``name`` is not a supported bitcode library.
144 BitcodeLibNotFoundError: If the bitcode library cannot be found.
145 """
146 finder = _FindBitcodeLib(name) 1pahifgjklnobcde
148 abs_path = finder.try_site_packages() 1ahifgjklnobcde
149 if abs_path is not None: 1ahifgjklnobcde
150 return LocatedBitcodeLib( 1obcd
151 name=name,
152 abs_path=str(abs_path),
153 filename=finder.filename,
154 found_via="site-packages",
155 )
157 abs_path = finder.try_with_conda_prefix() 1ahifgjklnbcde
158 if abs_path is not None: 1ahifgjklnbcde
159 return LocatedBitcodeLib( 1nbcd
160 name=name,
161 abs_path=str(abs_path),
162 filename=finder.filename,
163 found_via="conda",
164 )
166 abs_path = finder.try_with_cuda_home() 1ahifgjklbcde
167 if abs_path is not None: 1ahifgjklbcde
168 return LocatedBitcodeLib( 1ijklbcd
169 name=name,
170 abs_path=str(abs_path),
171 filename=finder.filename,
172 found_via="CUDA_PATH",
173 )
175 finder.raise_not_found_error() 1ahfge
178@functools.cache
179def find_bitcode_lib(name: str) -> str:
180 """Find the resolved absolute path to a bitcode library.
182 Raises:
183 ValueError: If ``name`` is not a supported bitcode library.
184 BitcodeLibNotFoundError: If the bitcode library cannot be found.
185 """
186 return locate_bitcode_lib(name).abs_path 1ahijklnoe