setup.py 7.44 KB
Newer Older
huteng.ht's avatar
huteng.ht committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
'''
Copyright (c) 2024 Beijing Volcano Engine Technology Ltd.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
'''

import os
import platform
19
import sys
huteng.ht's avatar
huteng.ht committed
20

21
22
23
import requests
import setuptools
import torch
huteng.ht's avatar
huteng.ht committed
24
from pkg_resources import parse_version
25
26
from setuptools import Extension, find_packages, setup
from torch.utils.cpp_extension import BuildExtension, CppExtension, include_paths
huteng.ht's avatar
huteng.ht committed
27
28
29
30
31
32

# initialize variables for compilation
IS_LINUX = platform.system() == "Linux"
IS_DARWIN = platform.system() == "Darwin"
IS_WINDOWS = platform.system() == "Windows"

33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
this_dir = os.path.dirname(os.path.abspath(__file__))


def get_option():
    if os.getenv("NPU_EXTENSION_ENABLED", "0") == "1":
        sys.argv.append("--npu_ext")
    elif "--cuda_ext" not in sys.argv and "--npu_ext" not in sys.argv and "--cpu_ext" not in sys.argv:
        print(
            '''No known extension specified, default to use --cuda_ext. Currently supported:
            --cuda_ext
            --npu_ext
            --cpu_ext'''
        )
        sys.argv.append("--cuda_ext")

huteng.ht's avatar
huteng.ht committed
48
49
50
51
52
53
54
55

def get_version():
    import importlib.util

    spec = importlib.util.spec_from_file_location("version", os.path.join("veturboio", "version.py"))
    m = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(m)

56
57
58
59
60
61
    if "--cpu_ext" in sys.argv:
        return m.__version__ + "+cpu"
    elif "--npu_ext" in sys.argv:
        return m.__version__ + "+npu"
    else:
        return m.__version__
huteng.ht's avatar
huteng.ht committed
62
63
64
65
66
67
68
69
70
71
72
73


def make_relative_rpath(path):
    if IS_DARWIN:
        return '-Wl,-rpath,@loader_path/' + path
    elif IS_WINDOWS:
        return ''
    else:
        return '-Wl,-rpath,$ORIGIN/' + path


def get_veturboio_extension():
74
    get_option()
huteng.ht's avatar
huteng.ht committed
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
    # prevent ninja from using too many resources
    try:
        import psutil

        num_cpu = len(psutil.Process().cpu_affinity())
        cpu_use = max(4, num_cpu - 1)
    except (ModuleNotFoundError, AttributeError):
        cpu_use = 4

    os.environ.setdefault("MAX_JOBS", str(cpu_use))
    # os.environ.setdefault("TORCH_CUDA_ARCH_LIST", "8.0;8.6")
    os.environ["TORCH_CUDA_ARCH_LIST"] = "8.0;8.6"

    define_macros = []

    # Before PyTorch1.8.0, when compiling CUDA code, `cxx` is a
    # required key passed to PyTorch. Even if there is no flag passed
    # to cxx, users also need to pass an empty list to PyTorch.
    # Since PyTorch1.8.0, it has a default value so users do not need
    # to pass an empty list anymore.
    # More details at https://github.com/pytorch/pytorch/pull/45956
96
    extra_compile_args = {'cxx': ['-fvisibility=hidden'], 'nvcc': ['-O3']}
huteng.ht's avatar
huteng.ht committed
97
98

    if parse_version(torch.__version__) <= parse_version('1.12.1'):
99
        extra_compile_args['cxx'].append('-std=c++14')
huteng.ht's avatar
huteng.ht committed
100
    else:
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
        extra_compile_args['cxx'].append('-std=c++17')

    name = "veturboio_ext"

    sources = [
        "veturboio/ops/csrc/pybind.cpp",
        "veturboio/ops/csrc/posix.cpp",
        "veturboio/ops/csrc/sfcs.cpp",
        "veturboio/ops/csrc/io_helper_cpu_common.cpp",
        "veturboio/ops/csrc/cipher.cpp",
    ]

    include_dirs = include_paths()
    include_dirs.append("veturboio/ops/csrc/include")

    torch_dir = os.path.join(os.path.dirname(torch.__file__), "lib")
    library_dirs = [torch_dir]
    library_dirs.append("veturboio/ops/csrc/lib")

    libraries = ["cloudfs", ":libfastcrypto_gpu.so.0.3"]
huteng.ht's avatar
huteng.ht committed
121
122
123

    extra_link_args = [make_relative_rpath("veturboio/ops/csrc/lib")]

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
    # Refer to: https://github.com/pytorch/pytorch/blob/main/torch/utils/cpp_extension.py#L918
    # In torch 2.0, this flag is False, and the *.so lib set this flag as False when building.
    # In newer torch, this flag is True, to keep compatibility with *.so lib, we set it False
    # to generate g++ flags '-D_GLIBCXX_USE_CXX11_ABI=0' when building veturboio_ext, otherwise
    # some 'undefine symbol' error of std::string will be thrown.
    torch._C._GLIBCXX_USE_CXX11_ABI = False

    if "--cuda_ext" in sys.argv:
        sys.argv.remove("--cuda_ext")

        extra_compile_args['nvcc'].append('-O3')

        sources.append("veturboio/ops/csrc/io_helper.cu")

        define_macros.append(("USE_CUDA", "1"))

        from torch.utils.cpp_extension import CUDAExtension

        return CUDAExtension(
            name=name,
            sources=sources,
            define_macros=define_macros,
            include_dirs=include_dirs,
            library_dirs=library_dirs,
            libraries=libraries,
            extra_compile_args=extra_compile_args,
            extra_link_args=extra_link_args,
        )
    else:
        extra_compile_args['cxx'].append('-O3')

        libraries.append("torch_cpu")
        libraries.append("torch_python")

        extra_link_args.append(f"-Wl,--rpath={torch_dir},--enable-new-dtags")

        if "--npu_ext" in sys.argv:
            sys.argv.remove("--npu_ext")

            sources.append("veturboio/ops/csrc/io_helper_npu.cpp")
            define_macros.append(("USE_NPU", "1"))

            return Extension(
                name=name,
                sources=sources,
                define_macros=define_macros,
                include_dirs=include_dirs,
                library_dirs=library_dirs,
                libraries=libraries,
                extra_compile_args=extra_compile_args,
                extra_link_args=extra_link_args,
            )
        elif "--cpu_ext" in sys.argv:
            sys.argv.remove("--cpu_ext")

            sources.append("veturboio/ops/csrc/io_helper_cpu.cpp")

            return Extension(
                name=name,
                sources=sources,
                define_macros=define_macros,
                include_dirs=include_dirs,
                library_dirs=library_dirs,
                libraries=libraries,
                extra_compile_args=extra_compile_args,
                extra_link_args=extra_link_args,
            )
huteng.ht's avatar
huteng.ht committed
191
192


193
194
195
196
class GetLibCfsCommand(setuptools.Command):
    """get libcfs from url"""

    description = 'get libcfs from url'
197
    user_options = [('src=', 's', 'source url of libcloudfs.so'), ('dst=', 'd', 'dest filepath of libcloudfs.so')]
198
199
200
201
202
203
204
205
206
207
208

    def initialize_options(self):
        from veturboio.utils.load_veturboio_ext import LIBCFS_DEFAULT_PATH, LIBCFS_DEFAULT_URL

        self.src = LIBCFS_DEFAULT_URL
        self.dst = LIBCFS_DEFAULT_PATH

    def finalize_options(self):
        pass

    def run(self):
209
        print(f"download libcloudfs.so from {self.src}, save to {self.dst}")
210
211
212
213
214
        r = requests.get(self.src, timeout=60)
        with open(self.dst, 'wb') as f:
            f.write(r.content)


huteng.ht's avatar
huteng.ht committed
215
216
217
218
219
220
221
222
223
224
setup(
    name="veturboio",
    version=get_version(),
    description="Effcient PyTorch IO libraray on Volcanic Engine",
    author="AML Team",
    ext_modules=[get_veturboio_extension()],
    packages=find_packages(exclude=("veturboio.ops.csrc.common.sfcs.lib")),
    install_requires=[
        "safetensors",
        "numpy",
225
        "netifaces",
huteng.ht's avatar
huteng.ht committed
226
227
        "loguru",
        "requests-unixsocket",
228
        "requests",
huteng.ht's avatar
huteng.ht committed
229
230
    ],
    include_package_data=True,
231
    cmdclass={"get_libcfs": GetLibCfsCommand, "build_ext": BuildExtension},
232
    dependency_links=['https://mirrors.ivolces.com/pypi/'],
huteng.ht's avatar
huteng.ht committed
233
)