Repository navigation
Expand file tree
/
Copy pathsetup.py
More file actions
378 lines (320 loc) · 13.3 KB
/
Copy pathsetup.py
File metadata and controls
378 lines (320 loc) · 13.3 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
"""
MCCL build script.
Builds the C++/Obj-C++ extension that provides the ProcessGroupMCCL backend on
macOS Apple Silicon.
If ``xcrun metal`` is available, ``mccl_shaders.metallib`` is built next to ``_C``.
If not (CLT-only machine), the build **warns and skips** metallib and still copies
``shaders.metal`` beside the extension for **runtime JIT**.
For **PyPI / release wheels**, set ``MCCL_REQUIRE_METALLIB=1`` so the build **fails**
when the Metal CLI is missing (ensures every wheel ships a ``.metallib``).
"""
import os
import platform
import shutil
import subprocess
from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext
# Paths relative to this file — pip/build isolation cwd is not always the repo root.
_REPO_ROOT = os.path.dirname(os.path.abspath(__file__))
def _shaders_metal_path() -> str:
"""Canonical shader source: ``csrc/metal/``; fallback ``mccl/shaders.metal`` (legacy copy)."""
for parts in (
("csrc", "metal", "shaders.metal"),
("mccl", "shaders.metal"),
):
p = os.path.join(_REPO_ROOT, *parts)
if os.path.isfile(p):
return p
return os.path.join(_REPO_ROOT, "csrc", "metal", "shaders.metal")
def _torch_include_dirs():
import sysconfig
import torch
from torch.utils.cpp_extension import include_paths
torch_root = os.path.join(os.path.dirname(torch.__file__), "include")
distributed_inc = os.path.join(torch_root, "torch", "csrc", "distributed")
python_inc = sysconfig.get_path("include")
return include_paths() + [distributed_inc, python_inc]
def _torch_library_dirs():
from torch.utils.cpp_extension import library_paths
return library_paths()
class MCCLBuildExt(build_ext):
"""Custom build_ext that handles mixed .cpp/.mm compilation on macOS."""
def build_extensions(self):
if platform.system() != "Darwin":
raise RuntimeError(
"MCCL can only be built on macOS. "
"This machine reports platform: " + platform.system()
)
arch = platform.machine()
if arch not in ("arm64", "aarch64"):
raise RuntimeError(
f"MCCL requires Apple Silicon (arm64). Detected: {arch}"
)
sdk_path = subprocess.check_output(
["xcrun", "--show-sdk-path"], text=True
).strip()
for ext in self.extensions:
ext.extra_compile_args = ext.extra_compile_args or []
ext.extra_link_args = ext.extra_link_args or []
cpp_flags = [
"-std=c++20",
"-O3",
"-flto=thin",
"-Wall",
"-Wextra",
"-Wno-unused-parameter",
"-fvisibility=hidden",
"-DMCCL_BUILD",
# apple-m1 is the floor for all Apple Silicon Macs; the old
# -march=armv8.5-a+crc excluded M1 (ARMv8.4-A).
"-mcpu=apple-m1",
"-isysroot", sdk_path,
]
objcpp_flags = cpp_flags + ["-fobjc-arc"]
ext._cpp_flags = cpp_flags
ext._objcpp_flags = objcpp_flags
ext.extra_link_args += [
"-flto=thin",
"-framework", "Metal",
"-framework", "Foundation",
"-framework", "MetalPerformanceShaders",
"-framework", "Accelerate",
"-isysroot", sdk_path,
]
super().build_extensions()
def build_extension(self, ext):
import torch
torch_lib = os.path.join(os.path.dirname(torch.__file__), "lib")
sources_cpp = [s for s in ext.sources if s.endswith(".cpp")]
sources_mm = [s for s in ext.sources if s.endswith(".mm")]
objects = []
for src in sources_cpp:
flags = ext._cpp_flags
if src.endswith("Registration.cpp"):
flags = [f for f in flags if f != "-fvisibility=hidden"]
obj = self._compile_single(src, flags, ext)
objects.append(obj)
for src in sources_mm:
obj = self._compile_single(src, ext._objcpp_flags, ext)
objects.append(obj)
ext.extra_link_args += [
f"-L{torch_lib}",
"-ltorch",
"-ltorch_cpu",
"-ltorch_python",
"-lc10",
f"-Wl,-rpath,{torch_lib}",
"-undefined", "dynamic_lookup",
]
self._link_shared_object(objects, ext)
def _compile_single(self, src, flags, ext):
import torch
obj = src + ".o"
obj_path = os.path.join(self.build_temp, obj)
os.makedirs(os.path.dirname(obj_path), exist_ok=True)
include_flags = []
for d in _torch_include_dirs() + (ext.include_dirs or []):
include_flags += ["-I", d]
cmd = ["clang++"] + flags + include_flags + ["-c", src, "-o", obj_path]
self.announce(f"Compiling {src}", level=2)
subprocess.check_call(cmd)
return obj_path
def _link_shared_object(self, objects, ext):
ext_path = self.get_ext_fullpath(ext.name)
os.makedirs(os.path.dirname(ext_path), exist_ok=True)
cmd = (
["clang++", "-shared", "-o", ext_path]
+ objects
+ (ext.extra_link_args or [])
)
self.announce(f"Linking {ext_path}", level=2)
subprocess.check_call(cmd)
self._fixup_rpath(ext_path)
out_dir = os.path.dirname(ext_path)
# Install source shaders before metallib so this always runs even if REQUIRE+metal fails.
# Editable / mixed layouts may load _C from mccl/mccl/ while setuptools links under build/;
# deploy beside every such directory so dladdr finds shaders.metal next to the loaded .so.
self._install_shaders_metal_for_ext(ext, out_dir)
self._compile_metallib(ext, out_dir)
@staticmethod
def _fixup_rpath(ext_path):
"""Replace the build-time torch rpath with a relative one that works at runtime."""
import torch
runtime_torch_lib = os.path.join(os.path.dirname(torch.__file__), "lib")
result = subprocess.run(
["otool", "-l", ext_path], capture_output=True, text=True
)
for i, line in enumerate(result.stdout.splitlines()):
if "path" in line and "torch" in line and "pip-build-env" in line:
stale = line.strip().split()[1]
subprocess.check_call([
"install_name_tool", "-delete_rpath", stale, ext_path
])
subprocess.run([
"install_name_tool", "-add_rpath", runtime_torch_lib, ext_path
], capture_output=True)
@staticmethod
def _detect_metal_std():
"""Pick the highest Metal language standard the host toolchain supports."""
mac_ver = platform.mac_ver()[0] # e.g. "15.1.1" or "14.7.2"
if mac_ver:
major = int(mac_ver.split(".")[0])
if major >= 15:
return "metal3.1"
return "metal3.0"
def _shader_bundle_dest_dirs(self, ext: Extension, primary_out_dir: str) -> list[str]:
"""Dirs that should hold ``shaders.metal`` / ``mccl_shaders.metallib`` next to ``_C``."""
dirs = [os.path.normpath(primary_out_dir)]
parts = ext.name.split(".")
if len(parts) >= 2:
pkg_path = os.path.normpath(os.path.join(_REPO_ROOT, *parts[:-1]))
if os.path.isdir(pkg_path):
dirs.append(pkg_path)
seen_real: set[str] = set()
unique: list[str] = []
for d in dirs:
try:
key = os.path.realpath(d)
except OSError:
key = d
if key not in seen_real:
seen_real.add(key)
unique.append(d)
return unique
def _install_shaders_metal_for_ext(self, ext: Extension, primary_out_dir: str) -> None:
"""Copy ``shaders.metal`` beside ``_C`` in every layout setuptools / editable may use."""
shader_src = _shaders_metal_path()
if not os.path.isfile(shader_src):
raise RuntimeError(
"MCCL build requires shaders.metal at "
f"{os.path.join(_REPO_ROOT, 'csrc', 'metal', 'shaders.metal')} "
"(restore from upstream mccl repo if missing)."
)
for d in self._shader_bundle_dest_dirs(ext, primary_out_dir):
os.makedirs(d, exist_ok=True)
dst = os.path.join(d, "shaders.metal")
shutil.copy2(shader_src, dst)
self.announce(f"Installed shaders.metal next to extension: {dst}", level=2)
def _compile_metallib(self, ext: Extension, output_dir: str) -> None:
shader_src = _shaders_metal_path()
if not os.path.isfile(shader_src):
raise RuntimeError(
f"MCCL build requires {shader_src} in the source tree."
)
require_metallib = os.environ.get("MCCL_REQUIRE_METALLIB", "").strip().lower() in (
"1",
"true",
"yes",
)
try:
subprocess.check_output(
["xcrun", "--find", "metal"], text=True, stderr=subprocess.STDOUT
)
except (subprocess.CalledProcessError, FileNotFoundError) as e:
msg = (
"Metal shader compiler not found (`xcrun metal`). Skipping precompiled "
"mccl_shaders.metallib; shaders.metal is still installed next to _C for runtime JIT. "
"For PyPI wheels, build on a Mac with full Xcode and set MCCL_REQUIRE_METALLIB=1 "
"so this step cannot be skipped silently."
)
if require_metallib:
raise RuntimeError(
"MCCL_REQUIRE_METALLIB=1 but `xcrun metal` is not available — "
"install full Xcode (not Command Line Tools only)."
) from e
self.warn(msg)
return
air_path = os.path.join(self.build_temp, "mccl_shaders.air")
lib_path = os.path.join(output_dir, "mccl_shaders.metallib")
os.makedirs(os.path.dirname(air_path), exist_ok=True)
sdk_path = subprocess.check_output(
["xcrun", "--show-sdk-path"], text=True
).strip()
metal_std = self._detect_metal_std()
self.announce(
f"Compiling {shader_src} -> .air (std={metal_std})", level=2
)
subprocess.check_call([
"xcrun", "metal",
"-c", shader_src,
"-o", air_path,
f"-std={metal_std}",
"-isysroot", sdk_path,
])
self.announce(f"Linking .air -> {lib_path}", level=2)
subprocess.check_call([
"xcrun", "metallib",
air_path,
"-o", lib_path,
])
if not os.path.isfile(lib_path):
raise RuntimeError(f"metallib build did not produce {lib_path}")
self.announce(f"Precompiled metallib: {lib_path}", level=2)
for d in self._shader_bundle_dest_dirs(ext, output_dir):
if os.path.normpath(d) == os.path.normpath(output_dir):
continue
dup = os.path.join(d, "mccl_shaders.metallib")
shutil.copy2(lib_path, dup)
self.announce(f"Synced metallib to {dup}", level=2)
CPP_SOURCES = [
"csrc/backend/ProcessGroupMCCL.cpp",
"csrc/backend/WorkMCCL.cpp",
"csrc/backend/Registration.cpp",
"csrc/backend/MPSDispatch.cpp",
"csrc/transport/TcpTransport.cpp",
"csrc/transport/Connection.cpp",
"csrc/runtime/ProgressEngine.cpp",
"csrc/runtime/Rendezvous.cpp",
"csrc/runtime/Watchdog.cpp",
"csrc/runtime/HealthMonitor.cpp",
"csrc/runtime/Metrics.cpp",
"csrc/runtime/MemoryPool.cpp",
"csrc/runtime/MCCLDeviceMutex.cpp",
"csrc/compression/Compression.cpp",
"csrc/compression/FP16Compression.cpp",
"csrc/compression/TopKCompression.cpp",
"csrc/transport/rdma/RdmaTransport.cpp",
"csrc/transport/rdma/IbvWrapper.cpp",
"csrc/transport/rdma/RdmaConnection.cpp",
"csrc/transport/rdma/SharedBuffer.cpp",
]
MM_SOURCES = [
"csrc/metal/MPSInterop.mm",
"csrc/metal/MetalKernels.mm",
"csrc/metal/AccelerateOps.mm",
"csrc/metal/EventSync.mm",
"csrc/transforms/StftCommon.mm",
"csrc/transforms/StftVdsp.mm",
"csrc/transforms/StftMetalKernels.mm",
"csrc/transforms/StftMetal.mm",
"csrc/transforms/Stft.mm",
]
def _csrc_build_depends() -> list[str]:
"""Headers and Metal sources. Extension ``sources`` are only .cpp/.mm, so without
this the sdist omits them and ``python -m build`` fails with a missing include.
"""
keep = {".hpp", ".h", ".metal"}
found: list[str] = []
root = os.path.join(_REPO_ROOT, "csrc")
for dirpath, _, filenames in os.walk(root):
for name in filenames:
if os.path.splitext(name)[1] in keep:
found.append(os.path.relpath(os.path.join(dirpath, name), _REPO_ROOT))
return sorted(found)
ext = Extension(
name="mccl._C",
sources=CPP_SOURCES + MM_SOURCES,
include_dirs=["csrc"],
depends=_csrc_build_depends(),
language="c++",
)
setup(
name="mccl",
version="6.9.1",
description="MPS-native ProcessGroup backend for PyTorch Distributed on Apple Silicon",
packages=["mccl"],
include_package_data=True,
ext_modules=[ext],
cmdclass={"build_ext": MCCLBuildExt},
python_requires=">=3.11",
)