Skip to content
Navigation Menu
{{ message }}
-
Notifications
You must be signed in to change notification settings - Fork 81
Expand file tree
/
Copy pathutils.py
More file actions
419 lines (364 loc) · 16.5 KB
/
Copy pathutils.py
File metadata and controls
419 lines (364 loc) · 16.5 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
# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.
# All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
import os
import multiprocessing
import subprocess
import sys
import shutil
from dataclasses import dataclass, field
import setuptools.command.build_ext
@dataclass
class BuildConfig:
cmake_only: bool = False
build_setup: bool = True
no_python: bool = False
no_cutlass: bool = False
no_test: bool = False
no_benchmark: bool = False
no_ninja: bool = False
build_with_ucc: bool = False
build_with_asan: bool = False
build_without_distributed: bool = False
explicit_error_check: bool = False
overwrite_version: bool = False
version_tag: str = None
build_type: str = "Release"
wheel_name: str = "nvfuser"
nvmmh_include_dir: str = ""
build_dir: str = ""
install_dir: str = ""
install_requires: list = field(default_factory=list)
extras_require: dict = field(default_factory=dict)
cpp_standard: int = 20
cutlass_max_jobs: int | None = None
enable_pch: bool = False
def check_env_flag_bool_default(name: str, default: str = "") -> bool:
if name not in os.environ:
return default
return os.getenv(name).upper() in ["ON", "1", "YES", "TRUE", "Y"]
def get_env_flag_bool(name: str) -> bool:
assert name in os.environ
return os.getenv(name).upper() in ["ON", "1", "YES", "TRUE", "Y"]
# Override BuildConfig with environment variables. Only change if variable
# exists. Do not use default to override argparse.
def override_build_config_from_env(config):
# Command line arguments don't work on PEP517 builds and will be silently ignored,
# so we need to pass those options as environment variables instead.
if "NVFUSER_BUILD_CMAKE_ONLY" in os.environ:
config.cmake_only = get_env_flag_bool("NVFUSER_BUILD_CMAKE_ONLY")
if "NVFUSER_BUILD_SETUP" in os.environ:
config.build_setup = get_env_flag_bool("NVFUSER_BUILD_SETUP")
if "NVFUSER_BUILD_NO_PYTHON" in os.environ:
config.no_python = get_env_flag_bool("NVFUSER_BUILD_NO_PYTHON")
if "NVFUSER_BUILD_NO_CUTLASS" in os.environ:
config.no_cutlass = get_env_flag_bool("NVFUSER_BUILD_NO_CUTLASS")
if "NVFUSER_BUILD_NO_TEST" in os.environ:
config.no_test = get_env_flag_bool("NVFUSER_BUILD_NO_TEST")
if "NVFUSER_BUILD_NO_BENCHMARK" in os.environ:
config.no_benchmark = get_env_flag_bool("NVFUSER_BUILD_NO_BENCHMARK")
if "NVFUSER_BUILD_NO_NINJA" in os.environ:
config.no_ninja = get_env_flag_bool("NVFUSER_BUILD_NO_NINJA")
if "NVFUSER_BUILD_WITH_UCC" in os.environ:
config.build_with_ucc = get_env_flag_bool("NVFUSER_BUILD_WITH_UCC")
if "NVFUSER_BUILD_WITH_ASAN" in os.environ:
config.build_with_asan = get_env_flag_bool("NVFUSER_BUILD_WITH_ASAN")
if "NVFUSER_BUILD_WITHOUT_DISTRIBUTED" in os.environ:
config.build_without_distributed = get_env_flag_bool(
"NVFUSER_BUILD_WITHOUT_DISTRIBUTED"
)
if "NVFUSER_BUILD_EXPLICIT_ERROR_CHECK" in os.environ:
config.explicit_error_check = get_env_flag_bool(
"NVFUSER_BUILD_EXPLICIT_ERROR_CHECK"
)
if "NVFUSER_BUILD_OVERWRITE_VERSION" in os.environ:
config.overwrite_version = get_env_flag_bool("NVFUSER_BUILD_OVERWRITE_VERSION")
if "NVFUSER_BUILD_VERSION_TAG" in os.environ:
config.version_tag = os.getenv("NVFUSER_BUILD_VERSION_TAG")
if "NVFUSER_BUILD_BUILD_TYPE" in os.environ:
config.build_type = os.getenv("NVFUSER_BUILD_BUILD_TYPE")
if "NVFUSER_BUILD_WHEEL_NAME" in os.environ:
config.wheel_name = os.getenv("NVFUSER_BUILD_WHEEL_NAME")
if "NVFUSER_BUILD_DIR" in os.environ:
config.build_dir = os.getenv("NVFUSER_BUILD_DIR")
if "NVFUSER_BUILD_INSTALL_DIR" in os.environ:
config.install_dir = os.getenv("NVFUSER_BUILD_INSTALL_DIR")
if "NVFUSER_BUILD_INSTALL_REQUIRES" in os.environ:
config.install_requires = os.getenv("NVFUSER_BUILD_INSTALL_REQUIRES").split(",")
if "NVFUSER_BUILD_EXTRAS_REQUIRE" in os.environ:
config.extras_require = eval(os.getenv("NVFUSER_BUILD_EXTRAS_REQUIRE"))
if "NVFUSER_BUILD_CPP_STANDARD" in os.environ:
config.cpp_standard = int(os.getenv("NVFUSER_BUILD_CPP_STANDARD"))
if "NVFUSER_BUILD_VERSION_TAG" in os.environ:
config.overwrite_version = True
config.version_tag = os.getenv("NVFUSER_BUILD_VERSION_TAG")
if "NVFUSER_CUTLASS_MAX_JOBS" in os.environ:
config.cutlass_max_jobs = int(os.getenv("NVFUSER_CUTLASS_MAX_JOBS"))
if "NVFUSER_BUILD_NVMMH_INCLUDE_DIR" in os.environ:
config.nvmmh_include_dir = os.getenv("NVFUSER_BUILD_NVMMH_INCLUDE_DIR")
if "NVFUSER_BUILD_ENABLE_PCH" in os.environ:
config.enable_pch = get_env_flag_bool("NVFUSER_BUILD_ENABLE_PCH")
def get_default_install_prefix():
cwd = os.path.dirname(os.path.abspath(__file__))
return os.path.join(cwd, "nvfuser_common")
class build_ext(setuptools.command.build_ext.build_ext):
def __init__(self, *args, **kwargs):
install_dir = kwargs.pop("install_dir", "")
self.install_dir = install_dir if install_dir else get_default_install_prefix()
super().__init__(*args, **kwargs)
def copy_library(self, ext, library_name):
# Copy files on necessity.
filename = self.get_ext_filename(self.get_ext_fullname(ext.name))
fileext = os.path.splitext(filename)[1]
libnvfuser_path = os.path.join(
os.path.join(self.install_dir, "lib"), f"{library_name}{fileext}"
)
assert os.path.exists(libnvfuser_path)
install_dst = os.path.join(self.build_lib, filename)
if not os.path.exists(os.path.dirname(install_dst)):
os.makedirs(os.path.dirname(install_dst))
self.copy_file(libnvfuser_path, install_dst)
def build_extension(self, ext):
if ext.name == "nvfuser_direct._C_DIRECT":
self.copy_library(ext, "libnvfuser_direct")
self.copy_shared_library("libnvfuser_codegen.so")
else:
super().build_extension(ext)
def copy_shared_library(self, lib_name):
# Copy shared library to lib/ subdirectory for package data
src_path = os.path.join(self.install_dir, "lib", lib_name)
if os.path.exists(src_path):
dst_dir = os.path.join(self.build_lib, "nvfuser_common", "lib")
if not os.path.exists(dst_dir):
os.makedirs(dst_dir)
dst_path = os.path.join(dst_dir, lib_name)
self.copy_file(src_path, dst_path)
class concat_third_party_license:
def __init__(self, directory="third_party"):
self.license_file = "LICENSE"
self.directory = directory
def __enter__(self):
# read original license file
with open(self.license_file, "r") as f:
self.nvfuser_license_txt = f.read()
licenses = {"LICENSE", "LICENSE.txt", "LICENSE.rst", "COPYING.BSD"}
# aggregated license, we key on project name
aggregated_license = {}
for root, dirs, files in os.walk(self.directory):
license = list(licenses & set(files))
if license:
project_name = root.split("/")[-1]
# let's worry about multiple license when we see it.
assert len(license) == 1
license_entry = os.path.join(root, license[0])
if project_name in aggregated_license:
# Only add it if the license is different
aggregated_license[project_name].append(license_entry)
else:
aggregated_license[project_name] = [license_entry]
return aggregated_license
def __exit__(self, exception_type, exception_value, traceback):
# restore original license file
with open(self.license_file, "w") as f:
f.write(self.nvfuser_license_txt)
try:
from wheel.bdist_wheel import bdist_wheel
except ImportError:
build_whl = None
else:
class build_whl(bdist_wheel):
def run(self):
with concat_third_party_license() as tp_licenses:
if len(tp_licenses) != 0:
with open("LICENSE", "a") as f:
f.write("\n\n")
f.write(
"NVIDIA/fuser depends on libraries with license listed below:"
)
for project_name, license_files in tp_licenses.items():
# check all license files are identical
with open(license_files[0], "r") as f:
license_ref = f.read()
def check_file(file_name):
with open(file_name, "r") as f:
return f.read() == license_ref
identical_flag = all(map(check_file, license_files[1:]))
if not identical_flag:
raise RuntimeError(
"inconsistent license found for project: ",
project_name,
" check its license files under: ",
license_files,
)
with open("LICENSE", "a") as f:
f.write("\n\nProject Name: " + project_name)
f.write("\nLicense Files:\n")
for file_name in license_files:
f.write("\t" + file_name)
f.write("\n" + license_ref)
# generate whl before we restore LICENSE
super().run()
def get_cmake_bin():
# TODO: double check cmake version here and retrieve later version if necessary
return "cmake"
def cmake(config, relative_path):
from tools.memory import get_available_memory_gb
# make build directories
cwd = os.path.dirname(os.path.abspath(__file__))
cmake_build_dir = (
os.path.join(cwd, "build") if not config.build_dir else config.build_dir
)
if not os.path.exists(cmake_build_dir):
os.makedirs(cmake_build_dir)
install_prefix = (
config.install_dir if config.install_dir else get_default_install_prefix()
)
from tools.gen_nvfuser_version import (
get_pytorch_use_distributed,
)
pytorch_use_distributed = get_pytorch_use_distributed()
def on_or_off(flag: bool) -> str:
return "ON" if flag else "OFF"
# generate cmake directory
#
# cmake options are sticky: when -DFOO=... isn't specified, cmake's option
# FOO prefers the cached value over the default value. This behavior
# confused me several times (e.g.
# https://github.com/NVIDIA/Fuser/pull/4319) when I ran `pip install -e`,
# so I chose to always pass these options even for default values. Doing so
# explicitly overrides cached values and ensures consistent behavior across
# clean and dirty builds.
cmd_str = [
get_cmake_bin(),
f"-DCMAKE_BUILD_TYPE={config.build_type}",
f"-DCMAKE_INSTALL_PREFIX={install_prefix}",
f"-DNVFUSER_CPP_STANDARD={config.cpp_standard}",
f"-DUSE_DISTRIBUTED={pytorch_use_distributed}",
f"-DNVFUSER_BUILD_WITH_ASAN={on_or_off(config.build_with_asan)}",
f"-DNVFUSER_STANDALONE_BUILD_WITH_UCC={on_or_off(config.build_with_ucc)}",
f"-DNVFUSER_EXPLICIT_ERROR_CHECK={on_or_off(config.explicit_error_check)}",
f"-DBUILD_TEST={on_or_off(not config.no_test)}",
f"-DBUILD_PYTHON={on_or_off(not config.no_python)}",
f"-DNVFUSER_DISABLE_CUTLASS={on_or_off(config.no_cutlass)}",
f"-DPython_EXECUTABLE={sys.executable}",
f"-DBUILD_NVFUSER_BENCHMARK={on_or_off(not config.no_benchmark)}",
f"-DNVFUSER_DISTRIBUTED={on_or_off(not config.build_without_distributed)}",
f"-DNVFUSER_USE_PCH={on_or_off(config.enable_pch)}",
"-B",
cmake_build_dir,
]
if config.cutlass_max_jobs:
cmd_str.append(f"-DCUTLASS_MAX_JOBS={config.cutlass_max_jobs}")
if config.nvmmh_include_dir:
cmd_str.append(f"-DNVMMH_INCLUDE_DIR={config.nvmmh_include_dir}")
if not config.no_ninja:
cmd_str.append("-G")
cmd_str.append("Ninja")
cmd_str.append(relative_path)
print(f"Configuring CMake with {' '.join(cmd_str)}")
subprocess.check_call(cmd_str)
max_jobs = multiprocessing.cpu_count()
mem_gb_per_task = 3 # Currently compilation of nvFuser souce code takes ~3GB of memory per task, we should adjust this value if it changes in the future.
available_mem = get_available_memory_gb()
if available_mem > 0:
max_jobs_mem = int(available_mem / mem_gb_per_task)
max_jobs = min(max_jobs, max_jobs_mem)
if not config.cmake_only:
# build binary
max_jobs = os.getenv("MAX_JOBS", str(max_jobs))
print(f"Using {max_jobs} jobs for compilation")
cmd_str = [
get_cmake_bin(),
"--build",
cmake_build_dir,
"--target",
"install",
"--",
"-j",
max_jobs,
]
subprocess.check_call(cmd_str)
def create_clean(relative_path):
class clean(setuptools.Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
import glob
gitignore_path = os.path.join(relative_path, ".gitignore")
assert os.path.exists(gitignore_path)
with open(gitignore_path, "r") as f:
ignores = f.read()
for entry in ignores.split("\n"):
# ignore comment in .gitignore
if len(entry) >= 1 and entry[0] != "#":
for filename in glob.glob(entry):
print("removing: ", filename)
try:
os.remove(filename)
except OSError:
shutil.rmtree(filename, ignore_errors=True)
return clean
def run(config, version_tag, relative_path):
from setuptools import Extension, setup, find_packages
# NOTE(crcrpar): Deliberately build basically two dynamic libraries here so that they can
# be treated as "nvfuser_package_data".
if config.build_setup:
cmake(config, relative_path)
if not config.cmake_only:
# NOTE: package include files for cmake
# TODO(crcrpar): Better avoid hardcoding `libnvfuser_codegen.so`
# might can be treated by using `exclude_package_data`.
nvfuser_common_package_data = [
"lib/libnvfuser_codegen.so",
"lib/libnvf_cutlass.so",
"include/nvfuser/*.h",
"include/nvfuser/struct.inl",
"include/nvfuser/C++20/type_traits",
"include/nvfuser/device_lower/*.h",
"include/nvfuser/device_lower/analysis/*.h",
"include/nvfuser/device_lower/pass/*.h",
"include/nvfuser/dynamic_type/*",
"include/nvfuser/dynamic_type/C++20/*",
"include/nvfuser/kernel_db/*.h",
"include/nvfuser/multidevice/*.h",
"include/nvfuser/ops/*.h",
"include/nvfuser/ir/*.h",
"include/nvfuser/scheduler/*.h",
"include/nvfuser/host_ir/*.h",
"include/nvfuser/id_model/*.h",
"share/cmake/nvfuser/NvfuserConfig*",
# TODO(crcrpar): it'd be better to ship the following two binaries.
# Would need some change in CMakeLists.txt.
# "bin/test_nvfuser",
# "bin/nvfuser_bench"
]
setup(
name=config.wheel_name,
version=version_tag,
url="https://github.com/NVIDIA/Fuser",
description="A Fusion Code Generator for NVIDIA GPUs (commonly known as 'nvFuser')",
packages=find_packages(),
ext_modules=[
Extension(name="nvfuser_direct._C_DIRECT", sources=[]),
],
license_files=("LICENSE",),
cmdclass={
"bdist_wheel": build_whl,
"build_ext": lambda *args, **kwargs: build_ext(
*args, install_dir=config.install_dir, **kwargs
),
"clean": create_clean(relative_path),
},
package_data={
"nvfuser_common": nvfuser_common_package_data,
},
install_requires=config.install_requires,
extras_require={
"test": ["numpy", "expecttest", "pytest"],
**config.extras_require,
},
license="BSD-3-Clause",
)
You can’t perform that action at this time.
