Repository navigation
Expand file tree
/
Copy pathsetup.py
More file actions
379 lines (329 loc) · 13.7 KB
/
Copy pathsetup.py
File metadata and controls
379 lines (329 loc) · 13.7 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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
import logging
import os
import shutil
import subprocess
from pathlib import Path
import setuptools
from setuptools import setup
from setuptools.command.build_ext import build_ext
logger = logging.getLogger(__name__)
# copy & modify from torch/utils/cpp_extension.py
def _find_platform_home(platform):
"""Find the install path for the specified platform (cuda/rocm/musa/xpu/mlu)."""
if platform == "cuda":
# Find CUDA home
home = os.environ.get('CUDA_HOME') or os.environ.get('CUDA_PATH')
if home is None:
compiler_path = shutil.which("nvcc")
if compiler_path is not None:
home = os.path.dirname(os.path.dirname(compiler_path))
else:
home = '/usr/local/cuda'
elif platform == "musa":
home = os.environ.get('MUSA_HOME') or os.environ.get('MUSA_PATH')
if home is None:
mcc = shutil.which("mcc")
if mcc is not None:
home = os.path.dirname(os.path.dirname(mcc))
else:
home = '/usr/local/musa'
elif platform == "mlu":
home = os.environ.get("NEUWARE_HOME", "/usr/local/neuware")
elif platform == "xpu":
home = os.environ.get('ONEAPI_ROOT')
if home is None:
icpx = _find_icpx()
if icpx is not None:
# bin/ -> latest/ -> compiler/ -> oneapi root
home = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(icpx))))
else:
home = '/opt/intel/oneapi'
else: # rocm/hip
# Find ROCm home
home = os.environ.get('ROCM_HOME') or os.environ.get('ROCM_PATH')
if home is None:
compiler_path = shutil.which("hipcc")
if compiler_path is not None:
home = os.path.dirname(os.path.dirname(compiler_path))
else:
home = '/opt/rocm'
return home
def _detect_platform():
"""Select a build backend based on the available toolchains and SDKs."""
forced = os.environ.get("TMS_PLATFORM")
if forced:
return forced
# Check for HIP first (since it might be preferred on AMD systems)
if shutil.which("hipcc") is not None:
return "hip"
elif shutil.which("nvcc") is not None:
return "cuda"
elif _has_musa():
return "musa"
elif _find_icpx() is not None:
return "xpu"
elif _has_mlu():
return "mlu"
else:
# Default to CUDA if neither is found
return "cuda"
def _has_musa():
"""True when MUSA headers and libs are available (or 'mcc' is on PATH)."""
home = os.environ.get("MUSA_HOME") or os.environ.get("MUSA_PATH")
if home and os.path.isfile(os.path.join(home, "include", "musa.h")):
return True
return shutil.which("mcc") is not None
def _has_mlu():
home = Path(_find_platform_home("mlu"))
return all((home / path).is_file() for path in (
"include/cn_api.h",
"include/cnrt.h",
"lib64/libcndrv.so",
"lib64/libcnrt.so",
))
class PlatformExtension(setuptools.Extension):
"""Unified extension class for both CUDA and HIP platforms."""
def __init__(self, name, sources, platform="cuda", *args, **kwargs):
self.platform = platform
super().__init__(name, sources, *args, **kwargs)
class build_platform_ext(build_ext):
"""Unified build extension class that handles both CUDA and HIP."""
def __init__(self, dist, platform="cuda"):
super().__init__(dist)
self.platform = platform
def build_extensions(self):
if self.platform == "hip":
# Set hipcc as the compiler for HIP
self.compiler.set_executable("compiler_so", "hipcc")
self.compiler.set_executable("compiler_cxx", "hipcc")
self.compiler.set_executable("linker_so", "hipcc --shared")
# Add extra compiler and linker flags for HIP
for ext in self.extensions:
ext.extra_compile_args = ['-fPIC']
ext.extra_link_args = ['-shared']
if self.platform == "xpu":
# Set icpx (Intel oneAPI SYCL compiler) for XPU, ABI-matched to torch.
icpx = _resolve_xpu_icpx()
self.compiler.set_executable("compiler_so", icpx)
self.compiler.set_executable("compiler_cxx", icpx)
self.compiler.set_executable("linker_so", f"{icpx} -shared")
for ext in self.extensions:
ext.extra_compile_args = ext.extra_compile_args + ['-fPIC', '-fsycl', '-fsycl-targets=spir64']
ext.extra_link_args = ext.extra_link_args + ['-fsycl', '-fsycl-targets=spir64', '-shared']
# For CUDA, use default compiler (no special setup needed)
build_ext.build_extensions(self)
def finalize_options(self):
if self.platform == "xpu":
icpx = _resolve_xpu_icpx()
os.environ["CC"] = icpx
os.environ["CXX"] = icpx
os.environ["LDSHARED"] = icpx + " -shared"
super().finalize_options()
def _create_ext_modules(platform):
"""Create extension modules based on the specified platform."""
# Common sources for all extensions
sources = [
'csrc/api_forwarder.cpp',
'csrc/core.cpp',
'csrc/disk_backend.cpp',
'csrc/entrypoint.cpp',
]
# Common define macros
common_macros = [('Py_LIMITED_API', '0x03090000')]
# Common compile arguments
extra_compile_args = ['-std=c++17', '-O3']
extra_link_args = []
# Platform-specific configurations
platform_home = Path(_find_platform_home(platform))
if platform == "hip":
# Add ROCm-specific source file for legacy chunked allocation (ROCm 6.x)
sources.append('csrc/hardware_amd_support.cpp')
include_dirs = [str(platform_home.resolve() / 'include')]
library_dirs = [str(platform_home.resolve() / 'lib')]
libraries = ['amdhip64', 'dl']
platform_macros = [('USE_ROCM', '1'), ('__HIP_PLATFORM_AMD__', '1')]
elif platform == "mlu":
include_dirs = [str(platform_home / "include")]
library_dirs = [str(platform_home / "lib64")]
libraries = ["cndrv", "cnrt", "dl"]
platform_macros = [("USE_MLU", "1")]
elif platform == "xpu":
sources.append('csrc/hardware_xpu_support.cpp')
icpx = _resolve_xpu_icpx()
include_dirs, library_dirs = _icpx_oneapi_include_lib(icpx)
libraries = ['sycl', 'ze_loader']
platform_macros = [('USE_XPU', '1')]
elif platform == "musa":
sources.append('csrc/hardware_musa_support.cpp')
include_dirs = [str((platform_home / 'include').resolve())]
library_dirs = [
str((platform_home / 'lib').resolve()),
str((platform_home / 'lib64').resolve()),
]
libraries = ['musa', 'musart', 'dl']
platform_macros = [('USE_MUSA', '1')]
else: # cuda
include_dirs = [str((platform_home / 'include').resolve())]
library_dirs = [
str((platform_home / 'lib64').resolve()),
str((platform_home / 'lib64/stubs').resolve()),
]
libraries = ['cuda', 'cudart']
platform_macros = [('USE_CUDA', '1')]
# Suffix the compiled .so files with the CUDA major they link against, so
# a single wheel can ship cu12 and cu13 variants side-by-side. `utils.py`
# picks the right one at runtime via torch.version.cuda / libcudart probe.
# ROCm and MUSA builds are single-variant and use unsuffixed binaries.
if platform == "cuda":
cuda_major = os.environ.get("TMS_CUDA_MAJOR")
if not cuda_major:
raise RuntimeError(
"TMS_CUDA_MAJOR env var must be set for CUDA builds "
"(use `make build-wheel-multi-cuda` or scripts/build_multi_cuda.sh)."
)
name_suffix = f"_cu{cuda_major}"
# RUNPATH (not RPATH) so the LD_PRELOAD-ed hook finds the pip CUDA runtime but LD_LIBRARY_PATH still wins
runtime_rel = f"nvidia/cu{cuda_major}/lib" if int(cuda_major) >= 13 else "nvidia/cuda_runtime/lib"
extra_link_args = [
"-Wl,--enable-new-dtags",
f"-Wl,-rpath,$ORIGIN/{runtime_rel}",
f"-Wl,-rpath,$ORIGIN/../{runtime_rel}",
]
else:
name_suffix = ""
# XPU only supports hook_mode='torch'
hook_variants = [
(f'torch_memory_saver_hook_mode_torch{name_suffix}', [('TMS_HOOK_MODE_TORCH', '1')]),
]
if platform != "xpu":
hook_variants.insert(
0,
(f'torch_memory_saver_hook_mode_preload{name_suffix}', [('TMS_HOOK_MODE_PRELOAD', '1')]),
)
ext_modules = [
PlatformExtension(
name,
sources,
platform=platform,
include_dirs=include_dirs,
library_dirs=library_dirs,
libraries=libraries,
define_macros=[
*common_macros,
*platform_macros,
*extra_macros,
],
py_limited_api=True,
extra_compile_args=extra_compile_args,
extra_link_args=extra_link_args,
)
for name, extra_macros in hook_variants
]
return ext_modules
# ============================== For Intel XPU ==============================
def _find_icpx():
"""Return the absolute path to icpx (Intel oneAPI SYCL compiler).
Honors $ICPX, then $PATH, then $ONEAPI_ROOT and common install locations.
"""
explicit = os.environ.get("ICPX")
if explicit and os.path.isfile(explicit):
return explicit
found = shutil.which("icpx")
if found:
return found
oneapi_root = os.environ.get("ONEAPI_ROOT")
search_roots = ([oneapi_root] if oneapi_root else []) + ['/opt/intel/oneapi']
for root in search_roots:
guess = os.path.join(root, 'compiler', 'latest', 'bin', 'icpx')
if os.path.isfile(guess):
return guess
return None
def _sycl_major_from_version_hpp(include_root):
"""__LIBSYCL_MAJOR_VERSION from <include_root>/sycl/version.hpp, or None."""
import re
try:
text = open(os.path.join(include_root, "sycl", "version.hpp")).read()
except OSError:
return None
m = re.search(r"__LIBSYCL_MAJOR_VERSION\s+(\d+)", text)
return int(m.group(1)) if m else None
def _icpx_sycl_major(icpx):
"""libsycl major that `icpx` builds against (NEEDED libsycl.so.<major>), or None.
compiler/<ver>/bin/icpx -> compiler/<ver>/include/sycl/version.hpp.
"""
if not icpx:
return None
base = os.path.dirname(os.path.dirname(os.path.realpath(icpx))) # compiler/<ver>
return _sycl_major_from_version_hpp(os.path.join(base, "include"))
def _torch_sycl_major():
"""libsycl major the installed torch.xpu needs (from libtorch_xpu.so), or None."""
import re
try:
import torch
except Exception:
return None
lib = os.path.join(os.path.dirname(torch.__file__), "lib", "libtorch_xpu.so")
try:
out = subprocess.run(["readelf", "-d", lib], capture_output=True, text=True).stdout
except Exception:
return None
m = re.search(r"libsycl\.so\.(\d+)", out)
return int(m.group(1)) if m else None
_RESOLVED_XPU_ICPX = None
def _resolve_xpu_icpx():
"""Pick an icpx whose libsycl major matches torch (mismatch corrupts the SYCL
runtime at load). Use the default icpx if it matches, torch's need is unknown,
or ICPX is pinned; else scan installed oneAPI compilers for a match.
"""
global _RESOLVED_XPU_ICPX
if _RESOLVED_XPU_ICPX is not None:
return _RESOLVED_XPU_ICPX
import glob
icpx = _find_icpx()
if icpx is None:
raise RuntimeError(
"Cannot find icpx (Intel oneAPI C++ compiler). Install oneAPI, "
"source setvars.sh, or set ICPX=/path/to/icpx."
)
want = _torch_sycl_major()
# Auto-switch only when needed and the user has not pinned ICPX explicitly.
if want is not None and not os.environ.get("ICPX") and _icpx_sycl_major(icpx) != want:
match = next(
(c for c in sorted(glob.glob("/opt/intel/oneapi/compiler/*/bin/icpx"), reverse=True)
if _icpx_sycl_major(c) == want),
None,
)
if match is None:
raise RuntimeError(
f"No Intel oneAPI compiler builds against libsycl.so.{want} (needed by your "
f"torch+xpu). Install a matching oneAPI, or set ICPX=/path/to/matching/icpx."
)
print(f"[torch_memory_saver] using {match} to match torch's libsycl.so.{want}")
icpx = match
_RESOLVED_XPU_ICPX = icpx
return icpx
def _icpx_oneapi_include_lib(icpx):
"""(include_dirs, library_dirs) from icpx's own compiler dir, so headers+libs
match the compiler we picked regardless of the sourced ONEAPI_ROOT."""
base = os.path.dirname(os.path.dirname(os.path.realpath(icpx))) # compiler/<ver>
include_dirs = [os.path.join(base, "include"), os.path.join(base, "include", "sycl")]
library_dirs = [os.path.join(base, "lib")]
return include_dirs, library_dirs
# =====================================================================
# Detect platform and set up accordingly
platform = _detect_platform()
print(f"Detected platform: {platform}")
# Create extension modules using unified function
ext_modules = _create_ext_modules(platform)
# Create unified build command class instance
class build_ext_for_platform(build_platform_ext):
def __init__(self, dist):
super().__init__(dist, platform=platform)
setup(
name='torch_memory_saver',
version='0.0.10',
ext_modules=ext_modules,
cmdclass={'build_ext': build_ext_for_platform},
python_requires=">=3.9",
packages=setuptools.find_packages(include=["torch_memory_saver", "torch_memory_saver.*"]),
)