-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_setup_helpers.py
More file actions
269 lines (219 loc) · 8.46 KB
/
Copy path_setup_helpers.py
File metadata and controls
269 lines (219 loc) · 8.46 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
import importlib
import os
import shutil
import subprocess
import sys
from typing import Optional, cast
from setuptools import Command, Extension
from setuptools.command.build_ext import build_ext
from setuptools.command.install import install
from setuptools.command.sdist import sdist
try:
_bdist_wheel_module = importlib.import_module(
"setuptools.command.bdist_wheel"
)
except Exception:
_bdist_wheel_module = importlib.import_module("wheel.bdist_wheel")
bdist_wheel_base = cast(type, _bdist_wheel_module.bdist_wheel)
protocol_compiler: Optional[str] = None
cuda_home_path: Optional[str] = None
torch_ready = False
def check_nvcc_installed(cuda_home: str) -> None:
try:
_ = subprocess.check_output(
[cuda_home + "/bin/nvcc", "-V"], universal_newlines=True
)
except Exception as exc:
raise RuntimeError(
"nvcc is not installed or not found in PATH. "
"Please ensure CUDA toolkit is installed and nvcc is available."
) from exc
def ensure_torch_environment() -> None:
global protocol_compiler
global cuda_home_path
global torch_ready
if torch_ready:
return
try:
torch = importlib.import_module("torch")
cpp_extension = importlib.import_module("torch.utils.cpp_extension")
except Exception as exc:
print(
"[WARNING] Unable to import torch, pre-compiling ops is disabled. "
"Please visit https://pytorch.org/ to install torch."
)
raise exc
torch_path = str(getattr(cpp_extension, "_TORCH_PATH"))
exec_ext = str(getattr(cpp_extension, "EXEC_EXT"))
cuda_home = getattr(cpp_extension, "CUDA_HOME")
protocol_compiler = os.path.join(torch_path, "bin", "protoc" + exec_ext)
cuda_home_path = None if cuda_home is None else str(cuda_home)
print(f"torch version: {torch.__version__}")
assert cuda_home_path is not None, "CUDA_HOME is not set"
check_nvcc_installed(cuda_home_path)
torch_ready = True
def is_ninja_available() -> bool:
try:
_ = subprocess.run(["ninja", "--version"], stdout=subprocess.PIPE)
except FileNotFoundError:
return False
return True
def remove_prefix(text: str, prefix: str) -> str:
if text.startswith(prefix):
return text[len(prefix) :]
return text
class cmake_build_ext(build_ext):
did_config: dict[str, bool] = {}
def run(self):
ensure_torch_environment()
if not self.extensions:
self.extensions = [
Extension("morphling._C", sources=[]),
Extension("morphling._Msg", sources=[]),
Extension("morphling._GreenCtx", sources=[]),
]
super().run()
def configure(self, ext: Extension) -> None:
cmake_lists_dir = os.path.abspath(getattr(ext, "cmake_lists_dir", "."))
if cmake_lists_dir in cmake_build_ext.did_config:
return
cmake_build_ext.did_config[cmake_lists_dir] = True
default_cfg = "Debug" if self.debug else "Release"
cfg = os.getenv("CMAKE_BUILD_TYPE", default_cfg)
outdir = os.path.abspath(
os.path.dirname(self.get_ext_fullpath(ext.name))
)
cmake_args = [
"-DCMAKE_POLICY_VERSION_MINIMUM=3.5",
f"-DCMAKE_BUILD_TYPE={cfg}",
f"-DCMAKE_LIBRARY_OUTPUT_DIRECTORY={outdir}",
f"-DCMAKE_RUNTIME_OUTPUT_DIRECTORY={outdir}",
f"-DCMAKE_ARCHIVE_OUTPUT_DIRECTORY={self.build_temp}",
"-DCMAKE_VERBOSE_MAKEFILE=ON",
f"-DMORPHLING_PYTHON_EXECUTABLE={sys.executable}",
]
if is_ninja_available():
build_tool = ["-G", "Ninja"]
cmake_args += [
"-DCMAKE_JOB_POOL_COMPILE:STRING=compile",
"-DCMAKE_JOB_POOLS:STRING=compile=8",
]
else:
build_tool = []
if os.environ.get("TEST") == "1":
cmake_args.append("-DBUILD_TESTS=ON")
else:
cmake_args.append("-DBUILD_TESTS=OFF")
ccache = shutil.which("ccache")
if ccache:
cmake_args += [
f"-DCMAKE_C_COMPILER_LAUNCHER={ccache}",
f"-DCMAKE_CXX_COMPILER_LAUNCHER={ccache}",
f"-DCMAKE_CUDA_COMPILER_LAUNCHER={ccache}",
]
_ = subprocess.check_call(
["cmake", cmake_lists_dir, *build_tool, *cmake_args],
cwd=self.build_temp,
)
if os.environ.get("TEST") == "1":
test_folder = os.path.join(self.build_temp, "tests", "cpp")
with open(
os.path.join(test_folder, "CTestTestfile.cmake"),
"r",
encoding="utf-8",
) as test_file:
for line in test_file.readlines():
if "add_test(" in line:
test_name = (
line.strip()
.split("add_test([=[")[-1]
.split("]=]")[0]
)
_ = subprocess.check_call(
["ninja", "-C", self.build_temp, test_name]
)
def build_extensions(self) -> None:
try:
_ = subprocess.check_output(["cmake", "--version"])
except OSError as exc:
raise RuntimeError("Cannot find CMake executable") from exc
if not os.path.exists(self.build_temp):
os.makedirs(self.build_temp)
for ext in self.extensions:
self.configure(ext)
ext_target_name = remove_prefix(ext.name, "morphling.")
build_args = [
"--build",
".",
"--target",
ext_target_name,
"-j",
"32",
]
_ = subprocess.check_call(
["cmake", *build_args], cwd=self.build_temp
)
print(self.build_temp, ext_target_name)
self.copy_extensions_to_source()
def copy_extensions_to_source(self) -> None:
"""Copy built .so extensions into the source package directory.
This is needed when the working directory is the project root (e.g.,
in Docker with WORKDIR /app), where Python finds the source package
before the installed one in site-packages. Without this step,
``import morphling._C`` fails because the .so files only exist in
the install tree, not next to __init__.py in the source tree.
"""
build_lib = self.build_lib
for ext in self.extensions:
fullname = self.get_ext_fullname(ext.name)
filename = self.get_ext_filename(fullname)
src = os.path.join(build_lib, filename)
if os.path.exists(src):
dest = (
filename # relative path, e.g. morphling/_C.cpython-...so
)
dest_dir = os.path.dirname(dest)
if dest_dir:
os.makedirs(dest_dir, exist_ok=True)
self.copy_file(src, dest)
def get_ext_filename(self, fullname):
for ext in self.extensions:
target_type = getattr(ext, "target_type", "shared")
if ext.name == fullname and target_type == "executable":
return fullname.replace(".", "/")
return super().get_ext_filename(fullname)
class BuildPackageProtos(Command):
description = "build grpc protobuf modules"
user_options = []
strict_mode = False
def initialize_options(self):
self.strict_mode = False
def finalize_options(self):
return None
def _build_package_proto(self, root: str, proto_file: str) -> None:
if protocol_compiler is None:
raise RuntimeError("Protocol compiler path is not initialized")
command = [
protocol_compiler,
"-I",
"./",
f"--python_out={root}",
proto_file,
]
_ = subprocess.check_call(command)
def run(self):
ensure_torch_environment()
self._build_package_proto(".", "morphling/proto/morphling.proto")
class CustomInstall(install):
def run(self):
self.run_command("build_ext")
self.run_command("build_package_protos")
super().run()
class CustomBuild(sdist):
def run(self):
self.run_command("build_package_protos")
super().run()
class CustomBdistWheel(bdist_wheel_base):
def run(self):
self.run_command("build_package_protos")
super().run()