forked from pytorch/executorch
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstall_utils.py
More file actions
Latest commit
285 lines (236 loc) · 9.36 KB
/
Copy pathinstall_utils.py
File metadata and controls
285 lines (236 loc) · 9.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
# Copyright (c) Meta Platforms, Inc. and affiliates.
# Copyright 2024-25 Arm Limited and/or its affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
importfunctools
importos
importplatform
importre
importsubprocess
importsys
fromtypingimportList, Optional
# Supported CUDA versions - modify this to add/remove supported versions
# Format: tuple of (major, minor) version numbers
SUPPORTED_CUDA_VERSIONS= (
(12, 6),
(13, 0),
(13, 2),
)
defis_cmake_option_on(
cmake_configuration_args: List[str], var_name: str, default: bool
) ->bool:
"""
Get a boolean CMake variable, from a list of CMake configuration arguments.
The var_name should not include the "-D" prefix.
Args:
cmake_configuration_args: List of CMake configuration arguments.
var_name: Name of the CMake variable.
default: Default boolean value if the variable is not set.
Returns:
Boolean value of the CMake variable.
"""
cmake_define=_extract_cmake_define(cmake_configuration_args, var_name)
return_normalize_cmake_bool(cmake_define, default)
defis_cuda_available() ->bool:
"""
Check if CUDA is available on the system by attempting to get the CUDA version.
Returns:
True if CUDA is available and supported, False otherwise.
"""
try:
_get_cuda_version()
returnTrue
exceptException:
returnFalse
defis_vulkan_available() ->bool:
"""
Check if the Vulkan shader compiler (glslc) is available on the system.
glslc is the only build-time dependency for the Vulkan backend; the Vulkan
loader itself is dlopen()ed at runtime via volk. Restricted to Linux and
Windows, the desktop GPU platforms the backend supports (macOS would require
MoltenVK).
glslc is looked up on PATH and, failing that, under $VULKAN_SDK/{bin,Bin} to
match the find_program() HINTS the build uses (see pybind.cmake and
ShaderLibrary.cmake): the Windows Vulkan SDK sets VULKAN_SDK but does not add
its bin directory to PATH, so a PATH-only probe would miss it there.
Returns:
True if glslc is available on a supported platform, False otherwise.
"""
ifsys.platformnotin ("linux", "win32"):
returnFalse
candidates= ["glslc"]
vulkan_sdk=os.environ.get("VULKAN_SDK")
ifvulkan_sdk:
glslc_name="glslc.exe"ifsys.platform=="win32"else"glslc"
candidates+= [
os.path.join(vulkan_sdk, "bin", glslc_name),
os.path.join(vulkan_sdk, "Bin", glslc_name),
]
forglslcincandidates:
try:
# Only the exit status matters, so skip text=True; keep the except
# tight to avoid masking things like UnicodeDecodeError.
subprocess.run([glslc, "--version"], capture_output=True, check=True)
returnTrue
except (OSError, subprocess.SubprocessError):
# glslc missing or not runnable -> unavailable; try the next candidate.
continue
returnFalse
@functools.lru_cache(maxsize=1)
def_get_cuda_version():
"""
Get the CUDA version installed on the system using nvcc command.
Returns a tuple (major, minor).
Raises:
RuntimeError: if nvcc is not found or version cannot be parsed
"""
try:
# Get CUDA version from nvcc (CUDA compiler)
nvcc_result=subprocess.run(
["nvcc", "--version"], capture_output=True, text=True, check=True
)
# Parse nvcc output for CUDA version
# Output contains line like "Cuda compilation tools, release 12.6, V12.6.68"
match=re.search(r"release (\d+)\.(\d+)", nvcc_result.stdout)
ifmatch:
major, minor=int(match.group(1)), int(match.group(2))
# Check if the detected version is supported
if (major, minor) notinSUPPORTED_CUDA_VERSIONS:
available_versions=", ".join(
[f"{maj}.{min}"formaj, mininSUPPORTED_CUDA_VERSIONS]
)
raiseRuntimeError(
f"Detected CUDA version {major}.{minor} is not supported. "
f"Supported versions: {available_versions}."
)
return (major, minor)
else:
raiseRuntimeError(
"Failed to parse CUDA version from nvcc output. "
"Ensure CUDA is properly installed."
)
exceptFileNotFoundError:
raiseRuntimeError(
"nvcc (CUDA compiler) is not found in PATH. Install the CUDA toolkit."
)
exceptsubprocess.CalledProcessErrorase:
raiseRuntimeError(
f"nvcc command failed with error: {e}. "
"Ensure CUDA is properly installed."
)
def_extract_cmake_define(args: List[str], name: str) ->Optional[str]:
prefix=f"-D{name}="
forarginargs:
ifarg.startswith(prefix):
returnarg[len(prefix) :]
returnNone
def_normalize_cmake_bool(value: Optional[str], default: bool=False) ->bool:
ifvalueisNone:
returndefault
normalized=value.strip().upper()
ifnormalizedin {"ON", "1", "TRUE", "YES"}:
returnTrue
ifnormalizedin {"OFF", "0", "FALSE", "NO"}:
returnFalse
returndefault
def_cuda_version_to_pytorch_suffix(major, minor):
"""
Generate PyTorch CUDA wheel suffix from CUDA version numbers.
Args:
major: CUDA major version (e.g., 12)
minor: CUDA minor version (e.g., 6)
Returns:
PyTorch wheel suffix string (e.g., "cu126")
"""
returnf"cu{major}{minor}"
def_get_pytorch_cuda_url(cuda_version, torch_nightly_url_base):
"""
Get the appropriate PyTorch CUDA URL for the given CUDA version.
Args:
cuda_version: tuple of (major, minor) version numbers
torch_nightly_url_base: Base URL for PyTorch nightly packages
Returns:
URL string for PyTorch CUDA packages
"""
major, minor=cuda_version
# Generate CUDA suffix (version validation is already done in _get_cuda_version)
cuda_suffix=_cuda_version_to_pytorch_suffix(major, minor)
returnf"{torch_nightly_url_base}/{cuda_suffix}"
@functools.lru_cache(maxsize=1)
defdetermine_torch_url(torch_nightly_url_base):
"""
Determine the appropriate PyTorch installation URL based on CUDA availability.
Uses @functools.lru_cache to avoid redundant CUDA detection and print statements.
Args:
torch_nightly_url_base: Base URL for PyTorch nightly packages
Returns:
URL string for PyTorch packages
"""
ifplatform.system().lower() =="windows":
print(
"Windows detected, using CPU-only PyTorch until CUDA support is available"
)
returnf"{torch_nightly_url_base}/cpu"
print("Attempting to detect CUDA via nvcc...")
try:
cuda_version=_get_cuda_version()
exceptExceptionaserr:
print(f"CUDA detection failed ({err}), using CPU-only PyTorch")
returnf"{torch_nightly_url_base}/cpu"
major, minor=cuda_version
print(f"Detected CUDA version: {major}.{minor}")
# Get appropriate PyTorch CUDA URL
torch_url=_get_pytorch_cuda_url(cuda_version, torch_nightly_url_base)
print(f"Using PyTorch URL: {torch_url}")
returntorch_url
# Prebuilt binaries for Intel-based macOS are no longer available on PyPI; users must compile from source.
# PyTorch stopped building macOS x86_64 binaries since version 2.3.0 (January 2024).
defis_intel_mac_os():
# Returns True if running on Intel macOS.
returnplatform.system().lower() =="darwin"andplatform.machine().lower() in (
"x86",
"x86_64",
"i386",
)
defpython_is_compatible():
# Scrape the version range from pyproject.toml, which should be in the current directory.
version_specifier=None
withopen("pyproject.toml", "r") asfile:
forlineinfile:
ifline.startswith("requires-python"):
match=re.search(r'"([^"]*)"', line)
ifmatch:
version_specifier=match.group(1)
break
ifnotversion_specifier:
print(
"WARNING: Skipping python version check: version range not found",
file=sys.stderr,
)
returnFalse
# Install the packaging module if necessary.
try:
importpackaging
exceptImportError:
subprocess.run(
[sys.executable, "-m", "pip", "install", "packaging"], check=True
)
# Compare the current python version to the range in version_specifier. Exits
# with status 1 if the version is not compatible, or with status 0 if the
# version is compatible or the logic itself fails.
try:
importpackaging.specifiers
importpackaging.version
python_version=packaging.version.parse(platform.python_version())
version_range=packaging.specifiers.SpecifierSet(version_specifier)
ifpython_versionnotinversion_range:
print(
f'ERROR: ExecuTorch does not support python version {python_version}: must satisfy "{version_specifier}"',
file=sys.stderr,
)
returnFalse
exceptExceptionase:
print(f"WARNING: Skipping python version check: {e}", file=sys.stderr)
returnTrue