setup.py 7.25 KB
Newer Older
Zhekai Zhang's avatar
Zhekai Zhang committed
1
import os
2
3
4
import re
import subprocess
import sys
Zhekai Zhang's avatar
Zhekai Zhang committed
5
6

import setuptools
7
8
import torch
from packaging import version as packaging_version
Muyang Li's avatar
Muyang Li committed
9
from torch.utils.cpp_extension import CUDA_HOME, BuildExtension, CUDAExtension
Zhekai Zhang's avatar
Zhekai Zhang committed
10

muyangli's avatar
muyangli committed
11

sxtyzhangzk's avatar
sxtyzhangzk committed
12
13
14
15
16
class CustomBuildExtension(BuildExtension):
    def build_extensions(self):
        for ext in self.extensions:
            if not "cxx" in ext.extra_compile_args:
                ext.extra_compile_args["cxx"] = []
sxtyzhangzk's avatar
sxtyzhangzk committed
17
18
            if not "nvcc" in ext.extra_compile_args:
                ext.extra_compile_args["nvcc"] = []
sxtyzhangzk's avatar
sxtyzhangzk committed
19
20
            if self.compiler.compiler_type == "msvc":
                ext.extra_compile_args["cxx"] += ext.extra_compile_args["msvc"]
sxtyzhangzk's avatar
sxtyzhangzk committed
21
                ext.extra_compile_args["nvcc"] += ext.extra_compile_args["nvcc_msvc"]
sxtyzhangzk's avatar
sxtyzhangzk committed
22
23
24
25
            else:
                ext.extra_compile_args["cxx"] += ext.extra_compile_args["gcc"]
        super().build_extensions()

26

27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
def get_sm_targets() -> list[str]:
    nvcc_path = os.path.join(CUDA_HOME, "bin/nvcc") if CUDA_HOME else "nvcc"
    try:
        nvcc_output = subprocess.check_output([nvcc_path, "--version"]).decode()
        match = re.search(r"release (\d+\.\d+), V(\d+\.\d+\.\d+)", nvcc_output)
        if match:
            nvcc_version = match.group(2)
        else:
            raise Exception("nvcc version not found")
        print(f"Found nvcc version: {nvcc_version}")
    except:
        raise Exception("nvcc not found")

    support_sm120 = packaging_version.parse(nvcc_version) >= packaging_version.parse("12.8")

    install_mode = os.getenv("NUNCHAKU_INSTALL_MODE", "FAST")
    if install_mode == "FAST":
        ret = []
        for i in range(torch.cuda.device_count()):
            capability = torch.cuda.get_device_capability(i)
            sm = f"{capability[0]}{capability[1]}"
            if sm == "120" and support_sm120:
                sm = "120a"
50
            assert sm in ["75", "80", "86", "89", "120a"], f"Unsupported SM {sm}"
51
52
53
54
            if sm not in ret:
                ret.append(sm)
    else:
        assert install_mode == "ALL"
55
        ret = ["75", "80", "86", "89"]
56
57
58
59
60
        if support_sm120:
            ret.append("120a")
    return ret


Zhekai Zhang's avatar
Zhekai Zhang committed
61
62
63
64
if __name__ == "__main__":
    fp = open("nunchaku/__version__.py", "r").read()
    version = eval(fp.strip().split()[-1])

65
66
67
68
    torch_version = torch.__version__.split("+")[0]
    torch_major_minor_version = ".".join(torch_version.split(".")[:2])
    version = version + "+torch" + torch_major_minor_version

Zhekai Zhang's avatar
Zhekai Zhang committed
69
70
71
72
73
74
75
76
    ROOT_DIR = os.path.dirname(__file__)

    INCLUDE_DIRS = [
        "src",
        "third_party/cutlass/include",
        "third_party/json/include",
        "third_party/mio/include",
        "third_party/spdlog/include",
Zhekai Zhang's avatar
Zhekai Zhang committed
77
        "third_party/Block-Sparse-Attention/csrc/block_sparse_attn",
Zhekai Zhang's avatar
Zhekai Zhang committed
78
79
    ]

Samuel Tesfai's avatar
Samuel Tesfai committed
80
    INCLUDE_DIRS = [os.path.join(ROOT_DIR, dir) for dir in INCLUDE_DIRS]
Zhekai Zhang's avatar
Zhekai Zhang committed
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95

    DEBUG = False

    def ncond(s) -> list:
        if DEBUG:
            return []
        else:
            return [s]

    def cond(s) -> list:
        if DEBUG:
            return [s]
        else:
            return []

muyangli's avatar
muyangli committed
96
97
98
99
100
    sm_targets = get_sm_targets()
    print(f"Detected SM targets: {sm_targets}", file=sys.stderr)

    assert len(sm_targets) > 0, "No SM targets found"

sxtyzhangzk's avatar
sxtyzhangzk committed
101
    GCC_FLAGS = ["-DENABLE_BF16=1", "-DBUILD_NUNCHAKU=1", "-fvisibility=hidden", "-g", "-std=c++20", "-UNDEBUG", "-Og"]
muyangli's avatar
muyangli committed
102
    MSVC_FLAGS = ["/DENABLE_BF16=1", "/DBUILD_NUNCHAKU=1", "/std:c++20", "/UNDEBUG", "/Zc:__cplusplus", "/FS"]
Zhekai Zhang's avatar
Zhekai Zhang committed
103
    NVCC_FLAGS = [
sxtyzhangzk's avatar
sxtyzhangzk committed
104
        "-DENABLE_BF16=1",
Zhekai Zhang's avatar
Zhekai Zhang committed
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
        "-DBUILD_NUNCHAKU=1",
        "-g",
        "-std=c++20",
        "-UNDEBUG",
        "-Xcudafe",
        "--diag_suppress=20208",  # spdlog: 'long double' is treated as 'double' in device code
        *cond("-G"),
        "-U__CUDA_NO_HALF_OPERATORS__",
        "-U__CUDA_NO_HALF_CONVERSIONS__",
        "-U__CUDA_NO_HALF2_OPERATORS__",
        "-U__CUDA_NO_HALF2_CONVERSIONS__",
        "-U__CUDA_NO_BFLOAT16_OPERATORS__",
        "-U__CUDA_NO_BFLOAT16_CONVERSIONS__",
        "-U__CUDA_NO_BFLOAT162_OPERATORS__",
        "-U__CUDA_NO_BFLOAT162_CONVERSIONS__",
muyangli's avatar
muyangli committed
120
        f"--threads={len(sm_targets)}",
Zhekai Zhang's avatar
Zhekai Zhang committed
121
122
123
124
        "--expt-relaxed-constexpr",
        "--expt-extended-lambda",
        "--ptxas-options=--allow-expensive-optimizations=true",
    ]
125

muyangli's avatar
muyangli committed
126
127
128
    if os.getenv("NUNCHAKU_BUILD_WHEELS", "0") == "0":
        NVCC_FLAGS.append("--generate-line-info")

129
130
131
    for target in sm_targets:
        NVCC_FLAGS += ["-gencode", f"arch=compute_{target},code=sm_{target}"]

Zhekai Zhang's avatar
Zhekai Zhang committed
132
    NVCC_MSVC_FLAGS = ["-Xcompiler", "/Zc:__cplusplus", "-Xcompiler", "/FS", "-Xcompiler", "/bigobj"]
Zhekai Zhang's avatar
Zhekai Zhang committed
133
134
135
136
137
138
139
140
141
142

    nunchaku_extension = CUDAExtension(
        name="nunchaku._C",
        sources=[
            "nunchaku/csrc/pybind.cpp",
            "src/interop/torch.cpp",
            "src/activation.cpp",
            "src/layernorm.cpp",
            "src/Linear.cpp",
            *ncond("src/FluxModel.cpp"),
muyangli's avatar
muyangli committed
143
            *ncond("src/SanaModel.cpp"),
Zhekai Zhang's avatar
Zhekai Zhang committed
144
            "src/Serialization.cpp",
145
            "src/Module.cpp",
Zhekai Zhang's avatar
Zhekai Zhang committed
146
147
148
149
150
151
            *ncond("third_party/Block-Sparse-Attention/csrc/block_sparse_attn/src/flash_fwd_hdim64_fp16_sm80.cu"),
            *ncond("third_party/Block-Sparse-Attention/csrc/block_sparse_attn/src/flash_fwd_hdim64_bf16_sm80.cu"),
            *ncond("third_party/Block-Sparse-Attention/csrc/block_sparse_attn/src/flash_fwd_hdim128_fp16_sm80.cu"),
            *ncond("third_party/Block-Sparse-Attention/csrc/block_sparse_attn/src/flash_fwd_hdim128_bf16_sm80.cu"),
            *ncond("third_party/Block-Sparse-Attention/csrc/block_sparse_attn/src/flash_fwd_block_hdim64_fp16_sm80.cu"),
            *ncond("third_party/Block-Sparse-Attention/csrc/block_sparse_attn/src/flash_fwd_block_hdim64_bf16_sm80.cu"),
152
153
154
155
156
157
            *ncond(
                "third_party/Block-Sparse-Attention/csrc/block_sparse_attn/src/flash_fwd_block_hdim128_fp16_sm80.cu"
            ),
            *ncond(
                "third_party/Block-Sparse-Attention/csrc/block_sparse_attn/src/flash_fwd_block_hdim128_bf16_sm80.cu"
            ),
Zhekai Zhang's avatar
Zhekai Zhang committed
158
159
160
            "src/kernels/activation_kernels.cu",
            "src/kernels/layernorm_kernels.cu",
            "src/kernels/misc_kernels.cu",
muyangli's avatar
muyangli committed
161
            "src/kernels/zgemm/gemm_w4a4.cu",
162
163
            "src/kernels/zgemm/gemm_w4a4_test.cu",
            "src/kernels/zgemm/gemm_w4a4_launch_fp16_int4.cu",
164
            "src/kernels/zgemm/gemm_w4a4_launch_fp16_int4_fasteri2f.cu",
165
166
167
            "src/kernels/zgemm/gemm_w4a4_launch_fp16_fp4.cu",
            "src/kernels/zgemm/gemm_w4a4_launch_bf16_int4.cu",
            "src/kernels/zgemm/gemm_w4a4_launch_bf16_fp4.cu",
muyangli's avatar
muyangli committed
168
            "src/kernels/zgemm/gemm_w8a8.cu",
169
            "src/kernels/zgemm/attention.cu",
muyangli's avatar
muyangli committed
170
            "src/kernels/dwconv.cu",
Zhekai Zhang's avatar
Zhekai Zhang committed
171
172
            "src/kernels/gemm_batched.cu",
            "src/kernels/gemm_f16.cu",
muyangli's avatar
muyangli committed
173
            "src/kernels/awq/gemm_awq.cu",
Zhekai Zhang's avatar
Zhekai Zhang committed
174
            "src/kernels/awq/gemv_awq.cu",
Zhekai Zhang's avatar
Zhekai Zhang committed
175
176
            *ncond("third_party/Block-Sparse-Attention/csrc/block_sparse_attn/flash_api.cpp"),
            *ncond("third_party/Block-Sparse-Attention/csrc/block_sparse_attn/flash_api_adapter.cpp"),
Zhekai Zhang's avatar
Zhekai Zhang committed
177
        ],
muyangli's avatar
muyangli committed
178
        extra_compile_args={"gcc": GCC_FLAGS, "msvc": MSVC_FLAGS, "nvcc": NVCC_FLAGS, "nvcc_msvc": NVCC_MSVC_FLAGS},
sxtyzhangzk's avatar
sxtyzhangzk committed
179
        include_dirs=INCLUDE_DIRS,
Zhekai Zhang's avatar
Zhekai Zhang committed
180
181
182
183
184
185
186
    )

    setuptools.setup(
        name="nunchaku",
        version=version,
        packages=setuptools.find_packages(),
        ext_modules=[nunchaku_extension],
sxtyzhangzk's avatar
sxtyzhangzk committed
187
        cmdclass={"build_ext": CustomBuildExtension},
Zhekai Zhang's avatar
Zhekai Zhang committed
188
    )