Debian Codegraph @

mesonbuild/modules/cuda.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2017-2025 The Meson development team
3
4 from __future__ import annotations
5
6 import dataclasses
7 import re
8 import typing as T
9
10 from ..mesonlib import listify, version_compare
11 from ..compilers.cuda import CudaCompiler
12 from ..interpreter.type_checking import NoneType
13
14 from . import NewExtensionModule, ModuleInfo
15
16 from ..interpreterbase import (
17 ContainerTypeInfo, InvalidArguments, KwargInfo, noKwargs, typed_kwargs, typed_pos_args,
18 )
19
20 if T.TYPE_CHECKING:
21 from typing_extensions import TypedDict
22
23 from . import ModuleState
24 from ..interpreter import Interpreter
25 from ..interpreterbase import TYPE_var
26
27 class ArchFlagsKwargs(TypedDict):
28 detected: T.Optional[T.List[str]]
29
30 AutoArch = T.Union[str, T.List[str]]
31
32
33 DETECTED_KW: KwargInfo[T.Union[None, T.List[str]]] = KwargInfo('detected', (ContainerTypeInfo(list, str), NoneType), listify=True)
34
35
36 @dataclasses.dataclass
37 class _CudaVersion:
38
39 meson: str
40 windows: str
41 linux: str
42
43 def compare(self, version: str, machine: str) -> T.Optional[str]:
44 if version_compare(version, f'>={self.meson}'):
45 return self.windows if machine == 'windows' else self.linux
46 return None
47
48
49 # Copied from: https://docs.nvidia.com/cuda/cuda-toolkit-release-notes/index.html#id7
50 _DRIVER_TABLE_VERSION: T.List[_CudaVersion] = [
51 _CudaVersion('13.0.2', 'unknown', '580.95.05'),
52 _CudaVersion('13.0.1', 'unknown', '580.82.07'),
53 _CudaVersion('13.0.0', 'unknown', '580.65.06'),
54 _CudaVersion('12.9.1', '576.57', '575.57.08'),
55 _CudaVersion('12.9.0', '576.02', '575.51.03'),
56 _CudaVersion('12.8.1', '572.61', '570.124.06'),
57 _CudaVersion('12.8.0', '570.65', '570.26'),
58 _CudaVersion('12.6.3', '561.17', '560.35.05'),
59 _CudaVersion('12.6.2', '560.94', '560.35.03'),
60 _CudaVersion('12.6.1', '560.94', '560.35.03'),
61 _CudaVersion('12.6.0', '560.76', '560.28.03'),
62 _CudaVersion('12.5.1', '555.85', '555.42.06'),
63 _CudaVersion('12.5.0', '555.85', '555.42.02'),
64 _CudaVersion('12.4.1', '551.78', '550.54.15'),
65 _CudaVersion('12.4.0', '551.61', '550.54.14'),
66 _CudaVersion('12.3.1', '546.12', '545.23.08'),
67 _CudaVersion('12.3.0', '545.84', '545.23.06'),
68 _CudaVersion('12.2.2', '537.13', '535.104.05'),
69 _CudaVersion('12.2.1', '536.67', '535.86.09'),
70 _CudaVersion('12.2.0', '536.25', '535.54.03'),
71 _CudaVersion('12.1.1', '531.14', '530.30.02'),
72 _CudaVersion('12.1.0', '531.14', '530.30.02'),
73 _CudaVersion('12.0.1', '528.33', '525.85.11'),
74 _CudaVersion('12.0.0', '527.41', '525.60.13'),
75 _CudaVersion('11.8.0', '522.06', '520.61.05'),
76 _CudaVersion('11.7.1', '516.31', '515.48.07'),
77 _CudaVersion('11.7.0', '516.01', '515.43.04'),
78 _CudaVersion('11.6.1', '511.65', '510.47.03'), # 11.6.2 is identical
79 _CudaVersion('11.6.0', '511.23', '510.39.01'),
80 _CudaVersion('11.5.1', '496.13', '495.29.05'), # 11.5.2 is identical
81 _CudaVersion('11.5.0', '496.04', '495.29.05'),
82 _CudaVersion('11.4.3', '472.50', '470.82.01'), # 11.4.4 is identical
83 _CudaVersion('11.4.1', '471.41', '470.57.02'), # 11.4.2 is identical
84 _CudaVersion('11.4.0', '471.11', '470.42.01'),
85 _CudaVersion('11.3.0', '465.89', '465.19.01'), # 11.3.1 is identical
86 _CudaVersion('11.2.2', '461.33', '460.32.03'),
87 _CudaVersion('11.2.1', '461.09', '460.32.03'),
88 _CudaVersion('11.2.0', '460.82', '460.27.03'),
89 _CudaVersion('11.1.1', '456.81', '455.32'),
90 _CudaVersion('11.1.0', '456.38', '455.23'),
91 _CudaVersion('11.0.3', '451.82', '450.51.06'), # 11.0.3.1 is identical
92 _CudaVersion('11.0.2', '451.48', '450.51.05'),
93 _CudaVersion('11.0.1', '451.22', '450.36.06'),
94 _CudaVersion('10.2.89', '441.22', '440.33'),
95 _CudaVersion('10.1.105', '418.96', '418.39'),
96 _CudaVersion('10.0.130', '411.31', '410.48'),
97 _CudaVersion('9.2.148', '398.26', '396.37'),
98 _CudaVersion('9.2.88', '397.44', '396.26'),
99 _CudaVersion('9.1.85', '391.29', '390.46'),
100 _CudaVersion('9.0.76', '385.54', '384.81'),
101 _CudaVersion('8.0.61', '376.51', '375.26'),
102 _CudaVersion('8.0.44', '369.30', '367.48'),
103 _CudaVersion('7.5.16', '353.66', '352.31'),
104 _CudaVersion('7.0.28', '347.62', '346.46'),
105 ]
106
107 class CudaModule(NewExtensionModule):
108
109 INFO = ModuleInfo('CUDA', '0.50.0', unstable=True)
110
111 def __init__(self, interp: Interpreter):
112 super().__init__()
113 self.methods.update({
114 "min_driver_version": self.min_driver_version,
115 "nvcc_arch_flags": self.nvcc_arch_flags,
116 "nvcc_arch_readable": self.nvcc_arch_readable,
117 })
118
119 @noKwargs
120 def min_driver_version(self, state: 'ModuleState',
121 args: T.List[TYPE_var],
122 kwargs: T.Dict[str, T.Any]) -> str:
123 argerror = InvalidArguments('min_driver_version must have exactly one positional argument: ' +
124 'a CUDA Toolkit version string. Beware that, since CUDA 11.0, ' +
125 'the CUDA Toolkit\'s components (including NVCC) are versioned ' +
126 'independently from each other (and the CUDA Toolkit as a whole).')
127 if len(args) != 1 or not isinstance(args[0], str):
128 raise argerror
129
130 cuda_version = args[0]
131
132 for d in _DRIVER_TABLE_VERSION:
133 driver_version = d.compare(cuda_version, state.environment.machines.host.system)
134 if driver_version is not None:
135 return driver_version
136 return 'unknown'
137
138 @typed_pos_args('cuda.nvcc_arch_flags', (str, CudaCompiler), varargs=str)
139 @typed_kwargs('cuda.nvcc_arch_flags', DETECTED_KW)
140 def nvcc_arch_flags(self, state: 'ModuleState',
141 args: T.Tuple[T.Union[CudaCompiler, str], T.List[str]],
142 kwargs: ArchFlagsKwargs) -> T.List[str]:
143 nvcc_arch_args = self._validate_nvcc_arch_args(args, kwargs)
144 ret = self._nvcc_arch_flags(*nvcc_arch_args)[0]
145 return ret
146
147 @typed_pos_args('cuda.nvcc_arch_readable', (str, CudaCompiler), varargs=str)
148 @typed_kwargs('cuda.nvcc_arch_readable', DETECTED_KW)
149 def nvcc_arch_readable(self, state: 'ModuleState',
150 args: T.Tuple[T.Union[CudaCompiler, str], T.List[str]],
151 kwargs: ArchFlagsKwargs) -> T.List[str]:
152 nvcc_arch_args = self._validate_nvcc_arch_args(args, kwargs)
153 ret = self._nvcc_arch_flags(*nvcc_arch_args)[1]
154 return ret
155
156 @staticmethod
157 def _break_arch_string(s: str) -> T.List[str]:
158 s = re.sub('[ \t\r\n,;]+', ';', s)
159 return s.strip(';').split(';')
160
161 @staticmethod
162 def _detected_cc_from_compiler(c: T.Union[str, CudaCompiler]) -> T.List[str]:
163 if isinstance(c, CudaCompiler):
164 return [c.detected_cc]
165 return []
166
167 def _validate_nvcc_arch_args(self, args: T.Tuple[T.Union[str, CudaCompiler], T.List[str]],
168 kwargs: ArchFlagsKwargs) -> T.Tuple[str, AutoArch, T.List[str]]:
169
170 compiler = args[0]
171 if isinstance(compiler, CudaCompiler):
172 cuda_version = compiler.version
173 else:
174 cuda_version = compiler
175
176 arch_list: AutoArch = args[1]
177 arch_list = listify([self._break_arch_string(a) for a in arch_list])
178 if len(arch_list) > 1 and not set(arch_list).isdisjoint({'All', 'Common', 'Auto'}):
179 raise InvalidArguments('''The special architectures 'All', 'Common' and 'Auto' must appear alone, as a positional argument!''')
180 arch_list = arch_list[0] if len(arch_list) == 1 else arch_list
181
182 detected = kwargs['detected'] if kwargs['detected'] is not None else self._detected_cc_from_compiler(compiler)
183 detected = [x for a in detected for x in self._break_arch_string(a)]
184 if not set(detected).isdisjoint({'All', 'Common', 'Auto'}):
185 raise InvalidArguments('''The special architectures 'All', 'Common' and 'Auto' must appear alone, as a positional argument!''')
186
187 return cuda_version, arch_list, detected
188
189 def _filter_cuda_arch_list(self, cuda_arch_list: T.List[str], lo: str, hi: T.Optional[str], saturate: str) -> T.List[str]:
190 """
191 Filter CUDA arch list (no codenames) for >= low and < hi architecture
192 bounds, and deduplicate.
193 Architectures >= hi are replaced with saturate.
194 """
195
196 filtered_cuda_arch_list = []
197 for arch in cuda_arch_list:
198 if arch:
199 if lo and version_compare(arch, '<' + lo):
200 continue
201 if hi and version_compare(arch, '>=' + hi):
202 arch = saturate
203 if arch not in filtered_cuda_arch_list:
204 filtered_cuda_arch_list.append(arch)
205 return filtered_cuda_arch_list
206
207 def _nvcc_arch_flags(self, cuda_version: str, cuda_arch_list: AutoArch, detected: T.List[str]) -> T.Tuple[T.List[str], T.List[str]]:
208 """
209 Using the CUDA Toolkit version and the target architectures, compute
210 the NVCC architecture flags.
211 """
212
213 # Replicates much of the logic of
214 # https://github.com/Kitware/CMake/blob/master/Modules/FindCUDA/select_compute_arch.cmake
215 # except that a bug with cuda_arch_list="All" is worked around by
216 # tracking both lower and upper limits on GPU architectures.
217
218 cuda_known_gpu_architectures = [] # noqa: E221
219 cuda_common_gpu_architectures = ['3.0', '3.5', '5.0'] # noqa: E221
220 cuda_hi_limit_gpu_architecture = None # noqa: E221
221 cuda_lo_limit_gpu_architecture = '2.0' # noqa: E221
222 cuda_all_gpu_architectures = ['3.0', '3.2', '3.5', '5.0'] # noqa: E221
223
224 # Fermi and Kepler support have been dropped since 12.0
225 if version_compare(cuda_version, '<12.0'):
226 cuda_known_gpu_architectures.extend(['Fermi', 'Kepler'])
227
228 # Everything older than Turing is dropped by 13.0
229 if version_compare(cuda_version, '<13.0'):
230 cuda_known_gpu_architectures.append('Maxwell')
231
232 if version_compare(cuda_version, '<7.0'):
233 cuda_hi_limit_gpu_architecture = '5.2'
234
235 if version_compare(cuda_version, '>=7.0'):
236 cuda_known_gpu_architectures += ['Kepler+Tegra', 'Kepler+Tesla', 'Maxwell+Tegra'] # noqa: E221
237 cuda_common_gpu_architectures += ['5.2'] # noqa: E221
238
239 if version_compare(cuda_version, '<8.0'):
240 cuda_common_gpu_architectures += ['5.2+PTX'] # noqa: E221
241 cuda_hi_limit_gpu_architecture = '6.0' # noqa: E221
242
243 if version_compare(cuda_version, '>=8.0'):
244 cuda_known_gpu_architectures += ['Pascal', 'Pascal+Tegra'] # noqa: E221
245 cuda_common_gpu_architectures += ['6.0', '6.1'] # noqa: E221
246 cuda_all_gpu_architectures += ['6.0', '6.1', '6.2'] # noqa: E221
247
248 if version_compare(cuda_version, '<9.0'):
249 cuda_common_gpu_architectures += ['6.1+PTX'] # noqa: E221
250 cuda_hi_limit_gpu_architecture = '7.0' # noqa: E221
251
252 if version_compare(cuda_version, '>=9.0'):
253 cuda_known_gpu_architectures += ['Volta', 'Xavier'] # noqa: E221
254 cuda_common_gpu_architectures += ['7.0'] # noqa: E221
255 cuda_all_gpu_architectures += ['7.0', '7.2'] # noqa: E221
256 # https://docs.nvidia.com/cuda/archive/9.0/cuda-toolkit-release-notes/index.html#unsupported-features
257 cuda_lo_limit_gpu_architecture = '3.0' # noqa: E221
258
259 if version_compare(cuda_version, '<10.0'):
260 cuda_common_gpu_architectures += ['7.2+PTX'] # noqa: E221
261 cuda_hi_limit_gpu_architecture = '8.0' # noqa: E221
262
263 if version_compare(cuda_version, '>=10.0'):
264 cuda_known_gpu_architectures += ['Turing'] # noqa: E221
265 cuda_common_gpu_architectures += ['7.5'] # noqa: E221
266 cuda_all_gpu_architectures += ['7.5'] # noqa: E221
267
268 if version_compare(cuda_version, '<11.0'):
269 cuda_common_gpu_architectures += ['7.5+PTX'] # noqa: E221
270 cuda_hi_limit_gpu_architecture = '8.0' # noqa: E221
271
272 # need to account for the fact that Ampere is commonly assumed to include
273 # SM8.0 and SM8.6 even though CUDA 11.0 doesn't support SM8.6
274 cuda_ampere_bin = ['8.0']
275 cuda_ampere_ptx = ['8.0']
276 if version_compare(cuda_version, '>=11.0'):
277 cuda_known_gpu_architectures += ['Ampere'] # noqa: E221
278 cuda_common_gpu_architectures += ['8.0'] # noqa: E221
279 cuda_all_gpu_architectures += ['8.0'] # noqa: E221
280 # https://docs.nvidia.com/cuda/archive/11.0/cuda-toolkit-release-notes/index.html#deprecated-features
281 cuda_lo_limit_gpu_architecture = '3.5' # noqa: E221
282
283 if version_compare(cuda_version, '<11.1'):
284 cuda_common_gpu_architectures += ['8.0+PTX'] # noqa: E221
285 cuda_hi_limit_gpu_architecture = '8.6' # noqa: E221
286
287 if version_compare(cuda_version, '>=11.1'):
288 cuda_ampere_bin += ['8.6'] # noqa: E221
289 cuda_ampere_ptx = ['8.6'] # noqa: E221
290
291 cuda_common_gpu_architectures += ['8.6'] # noqa: E221
292 cuda_all_gpu_architectures += ['8.6'] # noqa: E221
293
294 if version_compare(cuda_version, '<11.8'):
295 cuda_common_gpu_architectures += ['8.6+PTX'] # noqa: E221
296 cuda_hi_limit_gpu_architecture = '8.7' # noqa: E221
297
298 if version_compare(cuda_version, '>=11.8'):
299 cuda_known_gpu_architectures += ['Orin', 'Lovelace', 'Hopper'] # noqa: E221
300 cuda_common_gpu_architectures += ['8.9', '9.0', '9.0+PTX'] # noqa: E221
301 cuda_all_gpu_architectures += ['8.7', '8.9', '9.0'] # noqa: E221
302
303 if version_compare(cuda_version, '<12'):
304 cuda_hi_limit_gpu_architecture = '9.1' # noqa: E221
305
306 if version_compare(cuda_version, '>=12.0'):
307 # https://docs.nvidia.com/cuda/cuda-toolkit-release-notes/index.html#deprecated-features (Current)
308 # https://docs.nvidia.com/cuda/archive/12.0/cuda-toolkit-release-notes/index.html#deprecated-features (Eventual?)
309 cuda_lo_limit_gpu_architecture = '5.0' # noqa: E221
310
311 if version_compare(cuda_version, '<13'):
312 cuda_hi_limit_gpu_architecture = '10.0' # noqa: E221
313
314 if version_compare(cuda_version, '>=12.8'):
315 cuda_known_gpu_architectures.append('Blackwell')
316 cuda_common_gpu_architectures.extend(['10.0', '12.0'])
317 cuda_all_gpu_architectures.extend(['10.0', '12.0'])
318
319 if version_compare(cuda_version, '<13'):
320 # Yes, 12.8 and 12.9 support 10.1, but 13.0 doesn't
321 cuda_common_gpu_architectures.append('10.1')
322 cuda_all_gpu_architectures.append('10.1')
323 cuda_hi_limit_gpu_architecture = '12.1'
324
325 if version_compare(cuda_version, '>=12.9'):
326 cuda_common_gpu_architectures.extend(['10.3', '12.1'])
327 cuda_all_gpu_architectures.extend(['10.3', '12.1'])
328
329 if version_compare(cuda_version, '>=13.0'):
330 cuda_common_gpu_architectures.append('11.0')
331 cuda_all_gpu_architectures.append('11.0')
332 cuda_lo_limit_gpu_architecture = '7.5'
333
334 if version_compare(cuda_version, '<14'):
335 cuda_hi_limit_gpu_architecture = '12.1'
336
337 if not cuda_arch_list:
338 cuda_arch_list = 'Auto'
339
340 if cuda_arch_list == 'All': # noqa: E271
341 cuda_arch_list = cuda_known_gpu_architectures
342 elif cuda_arch_list == 'Common': # noqa: E271
343 cuda_arch_list = cuda_common_gpu_architectures
344 elif cuda_arch_list == 'Auto': # noqa: E271
345 if detected:
346 if isinstance(detected, list):
347 cuda_arch_list = detected
348 else:
349 cuda_arch_list = self._break_arch_string(detected)
350 cuda_arch_list = self._filter_cuda_arch_list(cuda_arch_list,
351 cuda_lo_limit_gpu_architecture,
352 cuda_hi_limit_gpu_architecture,
353 cuda_common_gpu_architectures[-1])
354 else:
355 cuda_arch_list = cuda_common_gpu_architectures
356 elif isinstance(cuda_arch_list, str):
357 cuda_arch_list = self._break_arch_string(cuda_arch_list)
358
359 cuda_arch_list = sorted(x for x in set(cuda_arch_list) if x)
360
361 cuda_arch_bin: T.List[str] = []
362 cuda_arch_ptx: T.List[str] = []
363 for arch_name in cuda_arch_list:
364 arch_bin: T.Optional[T.List[str]]
365 arch_ptx: T.Optional[T.List[str]]
366 add_ptx = arch_name.endswith('+PTX')
367 if add_ptx:
368 arch_name = arch_name[:-len('+PTX')]
369
370 if re.fullmatch('[0-9]+\\.[0-9](\\([0-9]+\\.[0-9]\\))?', arch_name):
371 arch_bin, arch_ptx = [arch_name], [arch_name]
372 else:
373 arch_bin, arch_ptx = {
374 'Fermi': (['2.0', '2.1(2.0)'], []),
375 'Kepler+Tegra': (['3.2'], []),
376 'Kepler+Tesla': (['3.7'], []),
377 'Kepler': (['3.0', '3.5'], ['3.5']),
378 'Maxwell+Tegra': (['5.3'], []),
379 'Maxwell': (['5.0', '5.2'], ['5.2']),
380 'Pascal': (['6.0', '6.1'], ['6.1']),
381 'Pascal+Tegra': (['6.2'], []),
382 'Volta': (['7.0'], ['7.0']),
383 'Xavier': (['7.2'], []),
384 'Turing': (['7.5'], ['7.5']),
385 'Ampere': (cuda_ampere_bin, cuda_ampere_ptx),
386 'Orin': (['8.7'], []),
387 'Lovelace': (['8.9'], ['8.9']),
388 'Hopper': (['9.0'], ['9.0']),
389 'Blackwell': (['10.0'], ['10.0']),
390 }.get(arch_name, (None, None))
391
392 if arch_bin is None:
393 raise InvalidArguments(f'Unknown CUDA Architecture Name {arch_name}!')
394
395 cuda_arch_bin += arch_bin
396
397 if add_ptx:
398 if not arch_ptx:
399 arch_ptx = arch_bin
400 cuda_arch_ptx += arch_ptx
401
402 cuda_arch_bin = sorted(set(cuda_arch_bin))
403 cuda_arch_ptx = sorted(set(cuda_arch_ptx))
404
405 nvcc_flags = []
406 nvcc_archs_readable = []
407
408 for arch in cuda_arch_bin:
409 arch, codev = re.fullmatch(
410 '([0-9]+\\.[0-9])(?:\\(([0-9]+\\.[0-9])\\))?', arch).groups()
411
412 if version_compare(arch, '<' + cuda_lo_limit_gpu_architecture):
413 continue
414 if cuda_hi_limit_gpu_architecture and version_compare(arch, '>=' + cuda_hi_limit_gpu_architecture):
415 continue
416
417 if codev:
418 arch = arch.replace('.', '')
419 codev = codev.replace('.', '')
420 nvcc_flags += ['-gencode', 'arch=compute_' + codev + ',code=sm_' + arch]
421 nvcc_archs_readable += ['sm_' + arch]
422 else:
423 arch = arch.replace('.', '')
424 nvcc_flags += ['-gencode', 'arch=compute_' + arch + ',code=sm_' + arch]
425 nvcc_archs_readable += ['sm_' + arch]
426
427 for arch in cuda_arch_ptx:
428 arch, codev = re.fullmatch(
429 '([0-9]+\\.[0-9])(?:\\(([0-9]+\\.[0-9])\\))?', arch).groups()
430
431 if codev:
432 arch = codev
433
434 if version_compare(arch, '<' + cuda_lo_limit_gpu_architecture):
435 continue
436 if cuda_hi_limit_gpu_architecture and version_compare(arch, '>=' + cuda_hi_limit_gpu_architecture):
437 continue
438
439 arch = arch.replace('.', '')
440 nvcc_flags += ['-gencode', 'arch=compute_' + arch + ',code=compute_' + arch]
441 nvcc_archs_readable += ['compute_' + arch]
442
443 return nvcc_flags, nvcc_archs_readable
444
445 def initialize(interp: Interpreter) -> CudaModule:
446 return CudaModule(interp)