Debian Codegraph @

mesonbuild/dependencies/cuda.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2013-2019 The Meson development team
3
4 from __future__ import annotations
5
6 import glob
7 import re
8 import os
9 import typing as T
10 from pathlib import Path
11
12 from .. import mesonlib
13 from .. import mlog
14 from .base import DependencyException, SystemDependency
15 from .detect import packages
16 from ..mesonlib import LibType
17
18 if T.TYPE_CHECKING:
19 from .._typing import ImmutableListProtocol
20 from ..environment import Environment
21 from ..compilers.compilers import Language, CompilerDict
22 from ..envconfig import MachineInfo
23 from .base import DependencyObjectKWs
24
25 TV_ResultTuple = T.Tuple[T.Optional[str], T.Optional[str], bool]
26
27 class CudaDependency(SystemDependency):
28
29 supported_languages: ImmutableListProtocol[Language] = ['cpp', 'c', 'cuda']
30 targets_dir = 'targets' # Directory containing CUDA targets.
31
32 def __init__(self, name: str, environment: 'Environment', kwargs: DependencyObjectKWs) -> None:
33 for_machine = kwargs['native']
34 compilers = environment.coredata.compilers[for_machine]
35 machine = environment.machines[for_machine]
36 if not kwargs.get('language'):
37 kwargs['language'] = self._detect_language(compilers)
38
39 if kwargs['language'] not in self.supported_languages:
40 raise DependencyException(f'Language \'{kwargs["language"]}\' is not supported by the CUDA Toolkit. Supported languages are {self.supported_languages}.')
41
42 super().__init__(name, environment, kwargs)
43 self.lib_modules: T.Dict[str, T.List[str]] = {}
44 self.requested_modules = kwargs.get('modules', [])
45 if not any(runtime in self.requested_modules for runtime in ['cudart', 'cudart_static']):
46 # By default, we prefer to link the static CUDA runtime, since this is what nvcc also does by default:
47 # https://docs.nvidia.com/cuda/cuda-compiler-driver-nvcc/index.html#cudart-none-shared-static-cudart
48 req_modules = ['cudart']
49 if kwargs.get('static') is not False:
50 req_modules = ['cudart_static']
51 self.requested_modules = req_modules + self.requested_modules
52
53 (self.cuda_path, self.version, self.is_found) = self._detect_cuda_path_and_version()
54 if not self.is_found:
55 return
56
57 if not os.path.isabs(self.cuda_path):
58 raise DependencyException(f'CUDA Toolkit path must be absolute, got \'{self.cuda_path}\'.')
59
60 # Cuda target directory relative to cuda path.
61 self.target_path = self._detect_target_path(machine)
62
63 # nvcc already knows where to find the CUDA Toolkit, but if we're compiling
64 # a mixed C/C++/CUDA project, we still need to make the include dir searchable
65 if self.language != 'cuda' or len(compilers) > 1:
66 self.incdir = os.path.join(self.cuda_path, self.target_path, 'include')
67 self.compile_args += [f'-I{self.incdir}']
68
69 arch_libdir = self._detect_arch_libdir()
70 self.libdir = os.path.join(self.cuda_path, self.target_path, arch_libdir)
71 mlog.debug('CUDA library directory is', mlog.bold(self.libdir))
72
73 # For legacy reasons cuda ignores the `prefer_static` option, and treats
74 # anything short of `static : false` as `static : true`. This is the
75 # opposite behavior of all other languages.
76 if kwargs.get('static') is None:
77 self.libtype = LibType.PREFER_STATIC
78
79 self.is_found = self._find_requested_libraries()
80
81 @classmethod
82 def _detect_language(cls, compilers: CompilerDict) -> Language:
83 for lang in cls.supported_languages:
84 if lang in compilers:
85 return lang
86 return list(compilers.keys())[0]
87
88 def _detect_cuda_path_and_version(self) -> TV_ResultTuple:
89 self.env_var = self._default_path_env_var()
90 mlog.debug('Default path env var:', mlog.bold(self.env_var))
91
92 version_reqs = self.version_reqs
93 if self.language == 'cuda':
94 nvcc_version = self._strip_patch_version(self.get_compiler().version)
95 mlog.debug('nvcc version:', mlog.bold(nvcc_version))
96 if version_reqs:
97 # make sure nvcc version satisfies specified version requirements
98 (found_some, not_found, found) = mesonlib.version_compare_many(nvcc_version, version_reqs)
99 if not_found:
100 msg = f'The current nvcc version {nvcc_version} does not satisfy the specified CUDA Toolkit version requirements {version_reqs}.'
101 return self._report_dependency_error(msg, (None, None, False))
102
103 # use nvcc version to find a matching CUDA Toolkit
104 version_reqs = [f'={nvcc_version}']
105 else:
106 nvcc_version = None
107
108 paths = [(path, self._cuda_toolkit_version(path), default) for (path, default) in self._cuda_paths()]
109 if version_reqs:
110 return self._find_matching_toolkit(paths, version_reqs, nvcc_version)
111
112 defaults = [(path, version) for (path, version, default) in paths if default]
113 if defaults:
114 return (defaults[0][0], defaults[0][1], True)
115
116 platform_msg = 'set the CUDA_PATH environment variable' if self._is_windows() \
117 else 'set the CUDA_PATH environment variable/create the \'/usr/local/cuda\' symbolic link'
118 msg = f'Please specify the desired CUDA Toolkit version (e.g. dependency(\'cuda\', version : \'>=10.1\')) or {platform_msg} to point to the location of your desired version.'
119 return self._report_dependency_error(msg, (None, None, False))
120
121 def _find_matching_toolkit(self, paths: T.List[TV_ResultTuple], version_reqs: T.List[str], nvcc_version: T.Optional[str]) -> TV_ResultTuple:
122 # keep the default paths order intact, sort the rest in the descending order
123 # according to the toolkit version
124 part_func: T.Callable[[TV_ResultTuple], bool] = lambda t: not t[2]
125 defaults_it, rest_it = mesonlib.partition(part_func, paths)
126 defaults = list(defaults_it)
127 paths = defaults + sorted(rest_it, key=lambda t: mesonlib.Version(t[1]), reverse=True)
128 mlog.debug(f'Search paths: {paths}')
129
130 if nvcc_version and defaults:
131 default_src = f"the {self.env_var} environment variable" if self.env_var else "the \'/usr/local/cuda\' symbolic link"
132 nvcc_warning = 'The default CUDA Toolkit as designated by {} ({}) doesn\'t match the current nvcc version {} and will be ignored.'.format(default_src, os.path.realpath(defaults[0][0]), nvcc_version)
133 else:
134 nvcc_warning = None
135
136 for (path, version, default) in paths:
137 (found_some, not_found, found) = mesonlib.version_compare_many(version, version_reqs)
138 if not not_found:
139 if not default and nvcc_warning:
140 mlog.warning(nvcc_warning)
141 return (path, version, True)
142
143 if nvcc_warning:
144 mlog.warning(nvcc_warning)
145 return (None, None, False)
146
147 def _detect_target_path(self, machine: MachineInfo) -> str:
148 # Non-Linux hosts: nothing to detect.
149 if not machine.is_linux():
150 return '.'
151
152 # Canonical target: '<arch>-<system>', e.g. 'x86_64-linux'.
153 canonical_target = f'{machine.cpu_family}-{machine.system}'
154 rel_path = os.path.join(self.targets_dir, canonical_target)
155 abs_path = os.path.join(self.cuda_path, rel_path)
156
157 # AArch64 may need the SBSA fallback.
158 if machine.cpu_family == 'aarch64' and not os.path.exists(abs_path):
159 rel_path = os.path.join(self.targets_dir, f"sbsa-{machine.system}")
160 abs_path = os.path.join(self.cuda_path, rel_path)
161 mlog.debug(
162 f'Canonical CUDA target "{self.targets_dir}/{canonical_target}" missing; '
163 f'falling back to "{rel_path}".'
164 )
165
166 mlog.debug(f'CUDA target resolved to "{rel_path}".')
167
168 if not os.path.exists(abs_path):
169 mlog.error(f'CUDA target "{rel_path}" does not exist.')
170
171 return rel_path
172
173 def _default_path_env_var(self) -> T.Optional[str]:
174 env_vars = ['CUDA_PATH'] if self._is_windows() else ['CUDA_PATH', 'CUDA_HOME', 'CUDA_ROOT']
175 env_vars = [var for var in env_vars if var in os.environ]
176 user_defaults = {os.environ[var] for var in env_vars}
177 if len(user_defaults) > 1:
178 mlog.warning('Environment variables {} point to conflicting toolkit locations ({}). Toolkit selection might produce unexpected results.'.format(', '.join(env_vars), ', '.join(user_defaults)))
179 return env_vars[0] if env_vars else None
180
181 def _cuda_paths(self) -> T.List[T.Tuple[str, bool]]:
182 return ([(os.environ[self.env_var], True)] if self.env_var else []) \
183 + (self._cuda_paths_win() if self._is_windows() else self._cuda_paths_nix())
184
185 def _cuda_paths_win(self) -> T.List[T.Tuple[str, bool]]:
186 env_vars = os.environ.keys()
187 return [(os.environ[var], False) for var in env_vars if var.startswith('CUDA_PATH_')]
188
189 def _cuda_paths_nix(self) -> T.List[T.Tuple[str, bool]]:
190 # include /usr/local/cuda default only if no env_var was found
191 pattern = '/usr/local/cuda-*' if self.env_var else '/usr/local/cuda*'
192 return [(path, os.path.basename(path) == 'cuda') for path in glob.iglob(pattern)]
193
194 toolkit_version_regex = re.compile(r'^CUDA Version\s+(.*)$')
195 path_version_win_regex = re.compile(r'^v(.*)$')
196 path_version_nix_regex = re.compile(r'^cuda-(.*)$')
197 cudart_version_regex = re.compile(r'#define\s+CUDART_VERSION\s+([0-9]+)')
198
199 def _cuda_toolkit_version(self, path: str) -> str:
200 version = self._read_toolkit_version_txt(path)
201 if version:
202 return version
203 version = self._read_cuda_runtime_api_version(path)
204 if version:
205 return version
206
207 mlog.debug('Falling back to extracting version from path')
208 path_version_regex = self.path_version_win_regex if self._is_windows() else self.path_version_nix_regex
209 try:
210 m = path_version_regex.match(os.path.basename(path))
211 if m:
212 return m.group(1)
213 else:
214 mlog.warning(f'Could not detect CUDA Toolkit version for {path}')
215 except Exception as e:
216 mlog.warning(f'Could not detect CUDA Toolkit version for {path}: {e!s}')
217
218 return '0.0'
219
220 def _read_cuda_runtime_api_version(self, path_str: str) -> T.Optional[str]:
221 path = Path(path_str)
222 for i in path.rglob('cuda_runtime_api.h'):
223 raw = i.read_text(encoding='utf-8')
224 m = self.cudart_version_regex.search(raw)
225 if not m:
226 continue
227 try:
228 vers_int = int(m.group(1))
229 except ValueError:
230 continue
231 # use // for floor instead of / which produces a float
232 major = vers_int // 1000
233 minor = (vers_int - major * 1000) // 10
234 return f'{major}.{minor}'
235 return None
236
237 def _read_toolkit_version_txt(self, path: str) -> T.Optional[str]:
238 # Read 'version.txt' at the root of the CUDA Toolkit directory to determine the toolkit version
239 version_file_path = os.path.join(path, 'version.txt')
240 try:
241 with open(version_file_path, encoding='utf-8') as version_file:
242 version_str = version_file.readline() # e.g. 'CUDA Version 10.1.168'
243 m = self.toolkit_version_regex.match(version_str)
244 if m:
245 return self._strip_patch_version(m.group(1))
246 except Exception as e:
247 mlog.debug(f'Could not read CUDA Toolkit\'s version file {version_file_path}: {e!s}')
248
249 return None
250
251 @classmethod
252 def _strip_patch_version(cls, version: str) -> str:
253 return '.'.join(version.split('.')[:2])
254
255 def _detect_arch_libdir(self) -> str:
256 machine = self.env.machines[self.for_machine]
257 arch = machine.cpu_family
258 msg = '{} architecture is not supported in {} version of the CUDA Toolkit.'
259 if machine.is_windows():
260 libdirs = {'x86': 'Win32', 'x86_64': 'x64'}
261 if arch not in libdirs:
262 raise DependencyException(msg.format(arch, 'Windows'))
263 return os.path.join('lib', libdirs[arch])
264 elif machine.is_linux():
265 return 'lib'
266 elif machine.is_darwin():
267 libdirs = {'x86_64': 'lib64'}
268 if arch not in libdirs:
269 raise DependencyException(msg.format(arch, 'macOS'))
270 return libdirs[arch]
271 else:
272 raise DependencyException('CUDA Toolkit: unsupported platform.')
273
274 def _find_requested_libraries(self) -> bool:
275 all_found = True
276
277 for module in self.requested_modules:
278 # You should only ever link to libraries inside the cuda tree, nothing outside of it.
279 # For instance, there is a
280 #
281 # - libnvidia-ml.so in stubs/ of the CUDA tree
282 # - libnvidia-ml.so in /usr/lib/ that is provided by the nvidia drivers
283 #
284 # Users should never link to the latter, since its ABI may change.
285 args = self.clib_compiler.find_library(module, [self.libdir, os.path.join(self.libdir, 'stubs')], self.libtype, ignore_system_dirs=True)
286
287 if args is None:
288 self._report_dependency_error(f'Couldn\'t find requested CUDA module \'{module}\'')
289 all_found = False
290 else:
291 mlog.debug(f'Link args for CUDA module \'{module}\' are {args}')
292 self.lib_modules[module] = args
293
294 return all_found
295
296 def _is_windows(self) -> bool:
297 return self.env.machines[self.for_machine].is_windows()
298
299 @T.overload
300 def _report_dependency_error(self, msg: str) -> None: ...
301
302 @T.overload
303 def _report_dependency_error(self, msg: str, ret_val: TV_ResultTuple) -> TV_ResultTuple: ... # noqa: F811
304
305 def _report_dependency_error(self, msg: str, ret_val: T.Optional[TV_ResultTuple] = None) -> T.Optional[TV_ResultTuple]: # noqa: F811
306 if self.required:
307 raise DependencyException(msg)
308
309 mlog.debug(msg)
310 return ret_val
311
312 def log_details(self) -> str:
313 module_str = ', '.join(self.requested_modules)
314 return 'modules: ' + module_str
315
316 def log_info(self) -> str:
317 return self.cuda_path if self.cuda_path else ''
318
319 def get_link_args(self, language: T.Optional[Language] = None, raw: bool = False) -> T.List[str]:
320 # when using nvcc to link, we should instead use the native driver options
321 REWRITE_MODULES = {
322 'cudart': ['-cudart', 'shared'],
323 'cudart_static': ['-cudart', 'static'],
324 'cudadevrt': ['-cudadevrt'],
325 }
326
327 args: T.List[str] = []
328 for lib in self.requested_modules:
329 link_args = self.lib_modules[lib]
330 if language == 'cuda' and lib in REWRITE_MODULES:
331 link_args = REWRITE_MODULES[lib]
332 mlog.debug(f'Rewriting module \'{lib}\' to \'{link_args}\'')
333 elif lib == 'cudart_static':
334 machine = self.env.machines[self.for_machine]
335 if machine.is_linux():
336 # extracted by running
337 # nvcc -v foo.o
338 link_args += ['-lrt', '-lpthread', '-ldl']
339
340 args += link_args
341
342 return args
343
344 packages['cuda'] = CudaDependency