setup.py 6.36 KB
Newer Older
Soumith Chintala's avatar
Soumith Chintala committed
1
#!/usr/bin/env python
2
import distutils.command.clean
3
import os
4
import re
moto's avatar
moto committed
5
import shutil
6
import subprocess
7
import sys
moto's avatar
moto committed
8
from pathlib import Path
9

10
import torch
flyingdown's avatar
flyingdown committed
11
from torch.utils.cpp_extension import ROCM_HOME
12
from setuptools import find_packages, setup
moto's avatar
moto committed
13
from tools import setup_helpers
14

moto's avatar
moto committed
15
ROOT_DIR = Path(__file__).parent.resolve()
16
17


flyingdown's avatar
flyingdown committed
18
def _run_cmd(cmd, shell=False):
19
    try:
flyingdown's avatar
flyingdown committed
20
        return subprocess.check_output(cmd, cwd=ROOT_DIR, stderr=subprocess.DEVNULL, shell=shell).decode("ascii").strip()
21
22
23
24
    except Exception:
        return None


moto's avatar
moto committed
25
def _get_version(sha):
26
27
    with open(ROOT_DIR / "version.txt", "r") as f:
        version = f.read().strip()
28
29
    if os.getenv("BUILD_VERSION"):
        version = os.getenv("BUILD_VERSION")
moto's avatar
moto committed
30
    elif sha is not None:
31
        version += "+" + sha[:7]
moto's avatar
moto committed
32
    return version
33
34


moto's avatar
moto committed
35
def _make_version_file(version, sha):
36
    sha = "Unknown" if sha is None else sha
flyingdown's avatar
flyingdown committed
37
38
39
40
41
    abi = _run_cmd(["echo '#include <string>' | gcc -x c++ -E -dM - | fgrep _GLIBCXX_USE_CXX11_ABI | awk '{print $3}'"], shell=True)
    dtk = _run_cmd(["cat", os.path.join(ROCM_HOME, '.info/rocm_version')])
    dtk = ''.join(dtk.split('.')[:2])
    torch_version = torch.__version__
    dcu_version = f"{version}.abi{abi}.dtk{dtk}.torch{torch_version}"
42
43
    version_path = ROOT_DIR / "torchaudio" / "version.py"
    with open(version_path, "w") as f:
moto's avatar
moto committed
44
45
        f.write(f"__version__ = '{version}'\n")
        f.write(f"git_version = '{sha}'\n")
flyingdown's avatar
flyingdown committed
46
47
48
49
50
51
        f.write(f"abi = 'abi{abi}'\n")
        f.write(f"dtk = '{dtk}'\n")
        f.write(f"torch_version = '{torch_version}'\n")
        f.write(f"dcu_version = '{dcu_version}'\n")
    return dcu_version

52

53

moto's avatar
moto committed
54
def _get_pytorch_version():
55
    if "PYTORCH_VERSION" in os.environ:
moto's avatar
moto committed
56
        return f"torch=={os.environ['PYTORCH_VERSION']}"
57
    return "torch"
58

moto's avatar
moto committed
59
60
61
62
63
64
65

class clean(distutils.command.clean.clean):
    def run(self):
        # Run default behavior first
        distutils.command.clean.clean.run(self)

        # Remove torchaudio extension
66
67
        for path in (ROOT_DIR / "torchaudio").glob("**/*.so"):
            print(f"removing '{path}'")
moto's avatar
moto committed
68
69
70
            path.unlink()
        # Remove build directory
        build_dirs = [
71
            ROOT_DIR / "build",
moto's avatar
moto committed
72
73
74
        ]
        for path in build_dirs:
            if path.exists():
75
                print(f"removing '{path}' (and everything under it)")
moto's avatar
moto committed
76
                shutil.rmtree(str(path), ignore_errors=True)
peterjc123's avatar
peterjc123 committed
77

78

moto's avatar
moto committed
79
def _get_packages(branch_name, tag):
80
81
82
83
84
85
86
87
    exclude = [
        "build*",
        "test*",
        "torchaudio.csrc*",
        "third_party*",
        "tools*",
    ]
    exclude_prototype = False
88
    if branch_name is not None and branch_name.startswith("release/"):
89
        exclude_prototype = True
90
    if tag is not None and re.match(r"v[\d.]+(-rc\d+)?", tag):
91
92
        exclude_prototype = True
    if exclude_prototype:
93
        print("Excluding torchaudio.prototype from the package.")
94
        exclude.append("torchaudio.prototype*")
95
96
97
    return find_packages(exclude=exclude)


98
def _init_submodule():
99
    print(" --- Initializing submodules")
100
    try:
101
102
        subprocess.check_call(["git", "submodule", "init"])
        subprocess.check_call(["git", "submodule", "update"])
103
    except Exception:
104
105
        print(" --- Submodule initalization failed")
        print("Please run:\n\tgit submodule update --init --recursive")
106
        sys.exit(1)
107
    print(" --- Initialized submodule")
108
109


moto's avatar
moto committed
110
def _parse_url(path):
111
    with open(path, "r") as file_:
moto's avatar
moto committed
112
        for line in file_:
113
            match = re.match(r"^\s*URL\s+(https:\/\/.+)$", line)
moto's avatar
moto committed
114
115
116
117
118
            if match:
                url = match.group(1)
                yield url


119
def _parse_sources():
120
    third_party_dir = ROOT_DIR / "third_party"
moto's avatar
moto committed
121
    libs = ["zlib", "bzip2", "lzma", "sox"]
122
    archive_dir = third_party_dir / "archives"
moto's avatar
moto committed
123
124
    archive_dir.mkdir(exist_ok=True)
    for lib in libs:
125
        cmake_file = third_party_dir / lib / "CMakeLists.txt"
moto's avatar
moto committed
126
127
128
        for url in _parse_url(cmake_file):
            path = archive_dir / os.path.basename(url)
            yield path, url
129
130


moto's avatar
moto committed
131
132
def _fetch_archives(src):
    for dest, url in src:
133
        if not dest.exists():
134
            print(f" --- Fetching {os.path.basename(dest)}")
135
136
137
138
            torch.hub.download_url_to_file(url, dest, progress=False)


def _fetch_third_party_libraries():
139
    _init_submodule()
140
    if os.name != "nt":
141
        _fetch_archives(_parse_sources())
142
143


moto's avatar
moto committed
144
def _main():
145
146
147
148
149
150
    sha = _run_cmd(["git", "rev-parse", "HEAD"])
    branch = _run_cmd(["git", "rev-parse", "--abbrev-ref", "HEAD"])
    tag = _run_cmd(["git", "describe", "--tags", "--exact-match", "@"])
    print("-- Git branch:", branch)
    print("-- Git SHA:", sha)
    print("-- Git tag:", tag)
moto's avatar
moto committed
151
    pytorch_package_dep = _get_pytorch_version()
152
    print("-- PyTorch dependency:", pytorch_package_dep)
moto's avatar
moto committed
153
    version = _get_version(sha)
154
    print("-- Building version", version)
moto's avatar
moto committed
155

flyingdown's avatar
flyingdown committed
156
    dcu_version = _make_version_file(version, sha)
157
    _fetch_third_party_libraries()
moto's avatar
moto committed
158
159
160

    setup(
        name="torchaudio",
flyingdown's avatar
flyingdown committed
161
        version=dcu_version,
moto's avatar
moto committed
162
163
        description="An audio package for PyTorch",
        url="https://github.com/pytorch/audio",
164
        author="Soumith Chintala, David Pollack, Sean Naren, Peter Goldsborough, Moto Hira, Caroline Chen, Jeff Hwang, Zhaoheng Ni, Xiaohui Zhang",
moto's avatar
moto committed
165
        author_email="soumith@pytorch.org",
166
167
        maintainer="Moto Hira, Caroline Chen, Jeff Hwang, Zhaoheng Ni, Xiaohui Zhang",
        maintainer_email="moto@meta.com",
moto's avatar
moto committed
168
169
170
171
172
173
174
175
176
177
178
179
180
181
        classifiers=[
            "Environment :: Plugins",
            "Intended Audience :: Developers",
            "Intended Audience :: Science/Research",
            "License :: OSI Approved :: BSD License",
            "Operating System :: MacOS :: MacOS X",
            "Operating System :: Microsoft :: Windows",
            "Operating System :: POSIX",
            "Programming Language :: C++",
            "Programming Language :: Python :: 3.7",
            "Programming Language :: Python :: 3.8",
            "Programming Language :: Python :: 3.9",
            "Programming Language :: Python :: Implementation :: CPython",
            "Topic :: Multimedia :: Sound/Audio",
182
            "Topic :: Scientific/Engineering :: Artificial Intelligence",
moto's avatar
moto committed
183
184
185
186
        ],
        packages=_get_packages(branch, tag),
        ext_modules=setup_helpers.get_ext_modules(),
        cmdclass={
187
188
            "build_ext": setup_helpers.CMakeBuild,
            "clean": clean,
moto's avatar
moto committed
189
190
191
192
193
194
        },
        install_requires=[pytorch_package_dep],
        zip_safe=False,
    )


195
if __name__ == "__main__":
moto's avatar
moto committed
196
    _main()