Repository navigation
Expand file tree
/
Copy pathsetup.py
More file actions
533 lines (461 loc) · 20.1 KB
/
Copy pathsetup.py
File metadata and controls
533 lines (461 loc) · 20.1 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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
import os
import re
import sys
import subprocess
import sysconfig
import setuptools
from glob import glob
import shutil
import site
from pathlib import Path
import torch
from torch.utils.cpp_extension import BuildExtension, CUDAExtension
from setuptools.command.install import install
from setuptools import Command
try:
import nanobind
except ImportError:
raise RuntimeError("nanobind not found. Install it with: pip install nanobind")
def _cuda_arch_versions(arch_list):
"""[8.9, 12.0] for a TORCH_CUDA_ARCH_LIST such as "8.9;12.0+PTX" or
"9.0a 10.0". None if an entry is not numeric (a name such as "Ada")."""
versions = []
for entry in re.split(r"[;,\s]+", arch_list.strip()):
match = re.match(r"\d+\.\d+", entry)
if entry and match is None:
return None
if entry:
versions.append(float(match.group()))
return versions
def _is_freethreaded():
return bool(sysconfig.get_config_var("Py_GIL_DISABLED"))
def _has_intel_rdma_nic():
"""Return True if an Intel RDMA NIC (irdma) is present on the system."""
ib_dir = Path("/sys/class/infiniband")
if not ib_dir.exists():
return False
try:
devices = os.listdir(ib_dir)
except OSError:
return False
return any(name.startswith("irdma") for name in devices)
_use_abi3 = not _is_freethreaded() and sys.version_info >= (3, 12)
class ABI3BuildExtension(BuildExtension):
"""Emit .abi3.so for nanobind stable-ABI extensions."""
def get_ext_filename(self, ext_name):
if _use_abi3:
return ext_name + ".abi3.so"
return super().get_ext_filename(ext_name)
PROJECT_ROOT = Path(os.path.dirname(__file__)).resolve()
class CustomInstall(install):
"""Custom install command that installs .so file to INSTALL_DIR"""
def run(self):
# Run the standard build first
self.run_command("build_ext")
# Get the install directory
python_site_packages = site.getsitepackages()[0]
install_dir = os.getenv(
"INSTALL_DIR", os.path.join(python_site_packages, "uccl")
)
os.makedirs(install_dir, exist_ok=True)
# Find the built .so file
build_lib = self.get_finalized_command("build_ext").build_lib
so_files = list(Path(build_lib).glob("ep*.so"))
if not so_files:
raise RuntimeError(f"Could not find built .so file in {build_lib}")
so_file = so_files[0]
dest_path = os.path.join(install_dir, so_file.name)
# Copy the .so file to the install directory
print(f"Installing {so_file.name} to {install_dir}")
shutil.copy2(so_file, dest_path)
if _use_abi3:
for old in Path(install_dir).glob("ep.cpython-*.so"):
print(f"Removing stale {old.name}")
old.unlink()
else:
for old in Path(install_dir).glob("ep.abi3.so"):
print(f"Removing stale {old.name}")
old.unlink()
print(f"Installation complete. Module installed as: {dest_path}")
class CustomClean(Command):
"""Custom clean command that removes build artifacts"""
description = "Clean build artifacts"
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
# Remove build directory
build_dir = PROJECT_ROOT / "build"
if build_dir.exists():
print(f"Removing {build_dir}")
shutil.rmtree(build_dir)
# Remove egg-info directory
for egg_info in PROJECT_ROOT.glob("*.egg-info"):
print(f"Removing {egg_info}")
shutil.rmtree(egg_info)
# Remove any .so files in the current directory
for so_file in PROJECT_ROOT.glob("*.so"):
print(f"Removing {so_file}")
so_file.unlink()
# Run make clean if Makefile exists
makefile = PROJECT_ROOT / "Makefile"
if makefile.exists():
print("Running make clean")
subprocess.run(["make", "clean"], cwd=PROJECT_ROOT)
print("Clean complete.")
if __name__ == "__main__":
cxx_flags = [
"-O3",
"-Wno-deprecated-declarations",
"-Wno-unused-variable",
"-Wno-sign-compare",
"-Wno-reorder",
"-Wno-attributes",
"-Wno-unused-result",
"-Wno-unused-function",
"-DNB_DOMAIN=uccl_ep",
]
nvcc_flags = ["-O3", "-Xcompiler", "-O3"]
sources = glob("./src/*.cu") + glob("./src/*.cpp") + glob("./src/*.cc")
libraries = ["ibverbs", "nl-3", "nl-route-3", "numa"]
include_dirs = [PROJECT_ROOT / "include", PROJECT_ROOT / ".." / "include"]
# Nanobind stable-ABI bindings
nb_dir = Path(nanobind.__file__).parent
include_dirs.extend([nb_dir / "include", nb_dir / "ext" / "robin_map" / "include"])
sources.append(str(nb_dir / "src" / "nb_combined.cpp"))
if _use_abi3:
abi_flags = ["-DPy_LIMITED_API=0x030C0000", "-DNB_STABLE_ABI=1"]
cxx_flags.extend(abi_flags)
nvcc_flags.extend(abi_flags)
max_num_gpus = os.getenv("MAX_NUM_GPUS")
if max_num_gpus:
max_num_gpus = int(max_num_gpus)
max_num_gpus_flag = f"-DMAX_NUM_GPUS={max_num_gpus}"
print(f"Building with MAX_NUM_GPUS={max_num_gpus}")
cxx_flags.append(max_num_gpus_flag)
nvcc_flags.append(max_num_gpus_flag)
# Collect header files for dependency tracking
header_files = []
for inc_dir in include_dirs:
header_files.extend(glob(str(inc_dir / "**" / "*.h"), recursive=True))
header_files.extend(glob(str(inc_dir / "**" / "*.hpp"), recursive=True))
header_files.extend(glob(str(inc_dir / "**" / "*.cuh"), recursive=True))
library_dirs = []
nvcc_dlink = []
extra_link_args = []
use_dmabuf = False
use_libfabric_cxi = int(os.getenv("USE_LIBFABRIC_CXI", "0"))
num_max_nvl_peers = os.getenv("NUM_MAX_NVL_PEERS")
if num_max_nvl_peers:
nvl_peers_flag = f"-DNUM_MAX_NVL_PEERS={int(num_max_nvl_peers)}"
print(f"Building with NUM_MAX_NVL_PEERS={int(num_max_nvl_peers)}")
cxx_flags.append(nvl_peers_flag)
nvcc_flags.append(nvl_peers_flag)
if use_libfabric_cxi:
print("Building with libfabric CXI transport support (USE_LIBFABRIC_CXI)")
cxx_flags.append("-DUSE_LIBFABRIC_CXI")
nvcc_flags.append("-DUSE_LIBFABRIC_CXI")
libraries.append("fabric")
libfabric_home = os.getenv("LIBFABRIC_HOME")
if libfabric_home:
include_dirs.append(Path(libfabric_home) / "include")
library_dirs.append(Path(libfabric_home) / "lib")
if torch.version.cuda:
# Add CUDA library directory to library_dirs
cuda_home = os.getenv("CUDA_HOME", "/usr/local/cuda")
library_dirs.append(str(Path(cuda_home) / "lib64"))
# EFA (Elastic Fabric Adapter) Detection
efa_home = os.getenv("EFA_HOME", "/opt/amazon/efa")
has_efa = os.path.exists(efa_home)
if has_efa:
print("EFA detected, building with EFA support")
else:
print("EFA not detected, building without EFA")
# Architecture Detection
arch = os.uname().machine
cpu_is_arm64 = arch == "aarch64"
# GPU Detection
gpu_name = ""
gpu_is_hopper = False
detected_compute_cap = None
try:
gpu_query = (
subprocess.check_output(
["nvidia-smi", "--query-gpu=name", "--format=csv,noheader"],
stderr=subprocess.DEVNULL,
)
.decode("ascii")
.strip()
.split("\n")[0]
)
gpu_name = gpu_query
gpu_is_hopper = "GH200" in gpu_name
# Auto-detect compute capability
compute_cap_query = (
subprocess.check_output(
[
"nvidia-smi",
"--query-gpu=compute_cap",
"--format=csv,noheader",
],
stderr=subprocess.DEVNULL,
)
.decode("ascii")
.strip()
.split("\n")[0]
)
detected_compute_cap = compute_cap_query.strip()
print(f"Detected GPU compute capability: {detected_compute_cap}")
except Exception as e:
print(f"Warning: Could not detect GPU info via nvidia-smi: {e}")
# GH200 (Grace Hopper) Detection
has_gh200 = cpu_is_arm64 and gpu_is_hopper
# UCCL_EP_DISABLE_GH200=1: build the generic Hopper + RDMA path. The GH200
# path allocates the atomic buffer with cudaMallocManaged, which plain
# ibv_reg_mr cannot register on IB without ODP ("Bad address").
if os.getenv("UCCL_EP_DISABLE_GH200", "0") == "1":
has_gh200 = False
if has_gh200:
print(
f"GH200 detected (GPU: {gpu_name}, CPU: {arch}), building with GH200 support"
)
else:
print("GH200 not detected, building without GH200 support")
# Add EFA flags if detected
if has_efa:
cxx_flags.append("-DEFA")
nvcc_flags.append("-DEFA")
include_dirs.append(Path(efa_home) / "include")
library_dirs.append(Path(efa_home) / "lib")
libraries.append("efa")
# DMA-BUF registration avoids nvidia_peermem/efa_nv_peermem.
# Set USE_DMABUF=1 to compile with this path.
use_dmabuf = int(os.getenv("USE_DMABUF", "0"))
if use_dmabuf:
print("Building with DMA-BUF GPU memory registration (USE_DMABUF)")
cxx_flags.append("-DUSE_DMABUF")
nvcc_flags.append("-DUSE_DMABUF")
else:
print("Building without DMA-BUF GPU memory registration")
# Add GH200 flags if detected
if has_gh200:
cxx_flags.append("-DUSE_GRACE_HOPPER")
nvcc_flags.append("-DUSE_GRACE_HOPPER")
# Add Intel RDMA NIC support: auto-detect irdma or USE_INTEL_RDMA_NIC=1
use_intel_rdma_nic = os.getenv("USE_INTEL_RDMA_NIC")
if use_intel_rdma_nic is None or use_intel_rdma_nic == "":
use_intel_rdma_nic = "1" if _has_intel_rdma_nic() else "0"
if int(use_intel_rdma_nic):
print("Building with Intel RDMA NIC support (INTEL_RDMA_NIC)")
cxx_flags.append("-DINTEL_RDMA_NIC")
nvcc_flags.append("-DINTEL_RDMA_NIC")
# Use auto-detected compute capability if available
if detected_compute_cap:
default_arch = detected_compute_cap
else:
# Fallback to 9.0 if detection failed
default_arch = "9.0"
# Targets before sm_90 (A100, L4, RTX 4090) lack TMA and the other SM90
# features, and ptxas rejects intranode.cu when they are compiled in.
# build.sh always passes DISABLE_SM90_FEATURES, as 0 by default.
disable_sm90 = int(os.getenv("DISABLE_SM90_FEATURES", 0))
target_versions = _cuda_arch_versions(
os.getenv("TORCH_CUDA_ARCH_LIST") or default_arch
)
pre_sm90 = [v for v in target_versions or [] if v < 9.0]
auto_disable_sm90 = bool(pre_sm90) and not disable_sm90
if auto_disable_sm90 and len(pre_sm90) < len(target_versions):
sys.exit(
"TORCH_CUDA_ARCH_LIST mixes targets below sm_90 with sm_90 or "
"newer. Build them separately, or set DISABLE_SM90_FEATURES=1 to "
"build all of them without SM90 features."
)
if auto_disable_sm90:
print("All CUDA targets are below sm_90: building without SM90 features")
if disable_sm90:
# Force A100 architecture
default_arch = "8.0"
if disable_sm90 or auto_disable_sm90:
# Disable some SM90 features: FP8, launch methods, and TMA
cxx_flags.append("-DDISABLE_SM90_FEATURES")
nvcc_flags.append("-DDISABLE_SM90_FEATURES")
else:
# For SM90 and above, add register usage optimization
if float(default_arch) >= 9.0:
nvcc_flags.extend(["--ptxas-options=--register-usage-level=10"])
# Set architecture environment variable before creating CUDAExtension
device_arch = os.getenv("TORCH_CUDA_ARCH_LIST", default_arch)
os.environ["TORCH_CUDA_ARCH_LIST"] = device_arch
else:
# AMD GPU Architecture Detection.
# Priority: PYTORCH_ROCM_ARCH > TORCH_CUDA_ARCH_LIST > rocminfo > fallback.
# In TheRock CI / manylinux build containers, rocminfo isn't installed
# and there is no GPU on the build host; arch must come from the env.
env_arch = os.getenv("PYTORCH_ROCM_ARCH") or os.getenv("TORCH_CUDA_ARCH_LIST")
detected_amd_arch = None
if env_arch:
print(f"Using AMD GPU arch from env: {env_arch}")
else:
try:
rocminfo_output = subprocess.check_output(
["rocminfo"], stderr=subprocess.DEVNULL
).decode("ascii")
# Parse rocminfo output to find GPU architecture (e.g., gfx942, gfx90a)
for line in rocminfo_output.split("\n"):
if "Name:" in line and "gfx" in line.lower():
# Extract architecture like "gfx942" from the line
for part in line.split():
if part.lower().startswith("gfx"):
detected_amd_arch = part.lower()
break
if detected_amd_arch:
break
if detected_amd_arch:
print(f"Detected AMD GPU architecture: {detected_amd_arch}")
except Exception as e:
print(
f"Warning: could not detect AMD GPU info via rocminfo: {e}"
" (perhaps inside a container)"
)
# Fallback: gfx942, the concrete compiler target for MI300A/MI300X
# supplied by TheRock's gfx94X-dcgpu package family.
device_arch = env_arch or detected_amd_arch or "gfx942"
for arch in device_arch.split(","):
nvcc_flags.append(f"--offload-arch={arch.lower()}")
# Disable SM90 features on AMD
cxx_flags.append("-DDISABLE_SM90_FEATURES")
nvcc_flags.append("-DDISABLE_SM90_FEATURES")
# Default the "aggressive atomic" path to ON for AMD builds so the
# cross-GPU tail-pointer stores in intranode/internode dispatch and
# combine actually drain prior vector-memory writes (s_waitcnt vmcnt).
# Vanilla acquire/release sys-scope atomics on CDNA do not, which
# causes the combine receiver to spin-wait on a stale shared_tail
# forever. Users can still opt out with
# UCCL_EP_ENABLE_AGGRESSIVE_ATOMIC=0 at runtime.
cxx_flags.append("-DUCCL_EP_DEFAULT_AGGRESSIVE_ATOMIC=1")
nvcc_flags.append("-DUCCL_EP_DEFAULT_AGGRESSIVE_ATOMIC=1")
# ROCm root discovery for TheRock-style installs.
# When ROCm comes from pip wheels (rocm-sdk), there is no /opt/rocm.
# Honor explicit HIP_HOME first, else query rocm-sdk, else /opt/rocm.
rocm_home = (
os.getenv("HIP_HOME") or os.getenv("ROCM_HOME") or os.getenv("ROCM_PATH")
)
if not rocm_home:
try:
rocm_home = (
subprocess.check_output(
["rocm-sdk", "path", "--root"],
stderr=subprocess.DEVNULL,
)
.decode("ascii")
.strip()
)
print(f"Discovered ROCm root via rocm-sdk: {rocm_home}")
except (FileNotFoundError, subprocess.CalledProcessError):
rocm_home = "/opt/rocm"
if rocm_home and Path(rocm_home).exists():
rocm_inc = Path(rocm_home) / "include"
rocm_lib = Path(rocm_home) / "lib"
if rocm_inc.exists():
include_dirs.append(rocm_inc)
if rocm_lib.exists():
library_dirs.append(rocm_lib)
os.environ.setdefault("ROCM_HOME", rocm_home)
os.environ.setdefault("ROCM_PATH", rocm_home)
os.environ.setdefault("HIP_HOME", rocm_home)
os.environ.setdefault("HIP_PATH", rocm_home)
print(f"Using ROCm root: {rocm_home}")
else:
print(
f"Warning: ROCm root '{rocm_home}' not found;"
" HIP toolchain may not link correctly."
)
os.environ["PYTORCH_ROCM_ARCH"] = device_arch
if int(os.getenv("DISABLE_BUILTIN_SHLF_SYNC", 1)):
# Disable built-in warp shuffle sync will have better performance in internode_combine kernel
cxx_flags.append("-DDISABLE_BUILTIN_SHLF_SYNC")
nvcc_flags.append("-DDISABLE_BUILTIN_SHLF_SYNC")
# cxx_flags.append("-DENABLE_FAST_DEBUG")
# nvcc_flags.append("-DENABLE_FAST_DEBUG")
# Per-expert batching path in dispatch-LL (default: disabled).
# Set PER_EXPERT_BATCHING=1 to compile with this path.
if int(os.getenv("PER_EXPERT_BATCHING", "0")):
cxx_flags.append("-DPER_EXPERT_BATCHING")
nvcc_flags.append("-DPER_EXPERT_BATCHING")
# Disable LD/ST tricks, as some CUDA version does not support `.L1::no_allocate`
# Only enable aggressive PTX instructions for SM 9.0+ (H100/H800/B200)
try:
arch_version = float(device_arch.strip())
if arch_version < 9.0:
os.environ["DISABLE_AGGRESSIVE_PTX_INSTRS"] = "1"
else:
# Enable aggressive PTX instructions for SM 9.0+
os.environ.setdefault("DISABLE_AGGRESSIVE_PTX_INSTRS", "0")
except (ValueError, AttributeError):
os.environ.setdefault("DISABLE_AGGRESSIVE_PTX_INSTRS", "1")
# Apply aggressive PTX instruction flag
if int(os.getenv("DISABLE_AGGRESSIVE_PTX_INSTRS", "0")):
cxx_flags.append("-DDISABLE_AGGRESSIVE_PTX_INSTRS")
nvcc_flags.append("-DDISABLE_AGGRESSIVE_PTX_INSTRS")
# Put them together
extra_compile_args = {
"cxx": cxx_flags,
"nvcc": nvcc_flags,
}
if len(nvcc_dlink) > 0:
extra_compile_args["nvcc_dlink"] = nvcc_dlink
# Convert Path objects to strings for include_dirs and library_dirs
include_dirs = [str(d) for d in include_dirs]
library_dirs = [str(d) for d in library_dirs]
# Summary
print("\n" + "=" * 60)
print("Build Summary")
print("=" * 60)
print(f" > Platform: {'ROCm' if torch.version.hip else 'CUDA'}")
if torch.version.cuda:
print(f" > Architecture: {arch}")
if gpu_name:
print(f" > GPU: {gpu_name}")
print(f" > EFA Support: {'Yes' if has_efa else 'No'}")
print(f" > GH200 Support: {'Yes' if has_gh200 else 'No'}")
print(f" > DMA-BUF Support: {'Yes' if use_dmabuf else 'No'}")
print(f" > libfabric CXI Support: {'Yes' if use_libfabric_cxi else 'No'}")
print(f" > Device Arch: {device_arch}")
print(f" > Sources: {len(sources)} files")
print(f" > Headers (tracked): {len(header_files)} files")
print(f" > Include Dirs: {include_dirs}")
print(f" > Library Dirs: {library_dirs}")
print(f" > Libraries: {libraries}")
print(f" > CXX Flags: {cxx_flags}")
print(f" > NVCC Flags: {nvcc_flags}")
print(f" > Link Flags: {extra_link_args}")
print("=" * 60 + "\n")
# noinspection PyBroadException
try:
cmd = ["git", "rev-parse", "--short", "HEAD"]
revision = "+" + subprocess.check_output(cmd).decode("ascii").rstrip()
except Exception as _:
revision = ""
setuptools.setup(
name="ep",
version="0.0.1" + revision,
ext_modules=[
CUDAExtension(
name="ep",
include_dirs=include_dirs,
library_dirs=library_dirs,
sources=sources,
libraries=libraries,
extra_compile_args=extra_compile_args,
extra_link_args=extra_link_args,
depends=header_files,
)
],
cmdclass={
"build_ext": ABI3BuildExtension,
"install": CustomInstall,
"clean": CustomClean,
},
)