"vscode:/vscode.git/clone" did not exist on "2c1a695ff111cadc200cf97d4c2cbfe95ebecb70"
extension.py 6.31 KB
Newer Older
1
import distutils.sysconfig
2
import os
moto's avatar
moto committed
3
4
5
6
import platform
import subprocess
from pathlib import Path

7
import torch
moto's avatar
moto committed
8
9
from setuptools import Extension
from setuptools.command.build_ext import build_ext
moto's avatar
moto committed
10
11

__all__ = [
12
13
    "get_ext_modules",
    "CMakeBuild",
moto's avatar
moto committed
14
15
16
17
]

_THIS_DIR = Path(__file__).parent.resolve()
_ROOT_DIR = _THIS_DIR.parent.parent.resolve()
18
_TORCHAUDIO_DIR = _ROOT_DIR / "torchaudio"
moto's avatar
moto committed
19

20

21
22
23
24
def _get_build(var, default=False):
    if var not in os.environ:
        return default

25
26
27
    val = os.environ.get(var, "0")
    trues = ["1", "true", "TRUE", "on", "ON", "yes", "YES"]
    falses = ["0", "false", "FALSE", "off", "OFF", "no", "NO"]
28
29
30
    if val in trues:
        return True
    if val not in falses:
31
        print(f"WARNING: Unexpected environment variable value `{var}={val}`. " f"Expected one of {trues + falses}")
32
33
34
    return False


35
_BUILD_SOX = False if platform.system() == "Windows" else _get_build("BUILD_SOX", True)
36
_BUILD_MAD = _get_build("BUILD_MAD", False)
37
_BUILD_KALDI = False if platform.system() == "Windows" else _get_build("BUILD_KALDI", True)
38
_BUILD_RNNT = _get_build("BUILD_RNNT", True)
39
_BUILD_CTC_DECODER = False if platform.system() == "Windows" else _get_build("BUILD_CTC_DECODER", True)
40
_USE_FFMPEG = _get_build("USE_FFMPEG", False)
41
42
_USE_ROCM = _get_build("USE_ROCM", torch.cuda.is_available() and torch.version.hip is not None)
_USE_CUDA = _get_build("USE_CUDA", torch.cuda.is_available() and torch.version.hip is None)
43
44
_USE_OPENMP = _get_build("USE_OPENMP", True) and "ATen parallel backend: OpenMP" in torch.__config__.parallel_info()
_TORCH_CUDA_ARCH_LIST = os.environ.get("TORCH_CUDA_ARCH_LIST", None)
moto's avatar
moto committed
45
46


moto's avatar
moto committed
47
def get_ext_modules():
48
    modules = [
49
50
        Extension(name="torchaudio.lib.libtorchaudio", sources=[]),
        Extension(name="torchaudio._torchaudio", sources=[]),
51
    ]
52
    if _BUILD_CTC_DECODER:
53
54
55
56
57
58
        modules.extend(
            [
                Extension(name="torchaudio.lib.libtorchaudio_decoder", sources=[]),
                Extension(name="torchaudio._torchaudio_decoder", sources=[]),
            ]
        )
59
    if _USE_FFMPEG:
60
        modules.append(Extension(name="torchaudio.lib.libtorchaudio_ffmpeg", sources=[]))
61
    return modules
moto's avatar
moto committed
62
63


moto's avatar
moto committed
64
65
66
67
68
# Based off of
# https://github.com/pybind/cmake_example/blob/580c5fd29d4651db99d8874714b07c0c49a53f8a/setup.py
class CMakeBuild(build_ext):
    def run(self):
        try:
69
            subprocess.check_output(["cmake", "--version"])
moto's avatar
moto committed
70
        except OSError:
71
            raise RuntimeError("CMake is not available.") from None
moto's avatar
moto committed
72
        super().run()
moto's avatar
moto committed
73
74

    def build_extension(self, ext):
75
76
77
78
79
80
        # Since two library files (libtorchaudio and _torchaudio) need to be
        # recognized by setuptools, we instantiate `Extension` twice. (see `get_ext_modules`)
        # This leads to the situation where this `build_extension` method is called twice.
        # However, the following `cmake` command will build all of them at the same time,
        # so, we do not need to perform `cmake` twice.
        # Therefore we call `cmake` only for `torchaudio._torchaudio`.
81
        if ext.name != "torchaudio._torchaudio":
82
83
            return

84
        extdir = os.path.abspath(os.path.dirname(self.get_ext_fullpath(ext.name)))
moto's avatar
moto committed
85
86
87
88
89
90
91
92
93
94
95

        # required for auto-detection of auxiliary "native" libs
        if not extdir.endswith(os.path.sep):
            extdir += os.path.sep

        cfg = "Debug" if self.debug else "Release"

        cmake_args = [
            f"-DCMAKE_BUILD_TYPE={cfg}",
            f"-DCMAKE_PREFIX_PATH={torch.utils.cmake_prefix_path}",
            f"-DCMAKE_INSTALL_PREFIX={extdir}",
96
            "-DCMAKE_VERBOSE_MAKEFILE=ON",
moto's avatar
moto committed
97
98
            f"-DPython_INCLUDE_DIR={distutils.sysconfig.get_python_inc()}",
            f"-DBUILD_SOX:BOOL={'ON' if _BUILD_SOX else 'OFF'}",
99
            f"-DBUILD_MAD:BOOL={'ON' if _BUILD_MAD else 'OFF'}",
100
            f"-DBUILD_KALDI:BOOL={'ON' if _BUILD_KALDI else 'OFF'}",
101
            f"-DBUILD_RNNT:BOOL={'ON' if _BUILD_RNNT else 'OFF'}",
102
            f"-DBUILD_CTC_DECODER:BOOL={'ON' if _BUILD_CTC_DECODER else 'OFF'}",
moto's avatar
moto committed
103
            "-DBUILD_TORCHAUDIO_PYTHON_EXTENSION:BOOL=ON",
104
            f"-DUSE_ROCM:BOOL={'ON' if _USE_ROCM else 'OFF'}",
Caroline Chen's avatar
Caroline Chen committed
105
            f"-DUSE_CUDA:BOOL={'ON' if _USE_CUDA else 'OFF'}",
moto's avatar
moto committed
106
            f"-DUSE_OPENMP:BOOL={'ON' if _USE_OPENMP else 'OFF'}",
107
            f"-DUSE_FFMPEG:BOOL={'ON' if _USE_FFMPEG else 'OFF'}",
moto's avatar
moto committed
108
        ]
109
        build_args = ["--target", "install"]
110
111
112
113
        # Pass CUDA architecture to cmake
        if _TORCH_CUDA_ARCH_LIST is not None:
            # Convert MAJOR.MINOR[+PTX] list to new style one
            # defined at https://cmake.org/cmake/help/latest/prop_tgt/CUDA_ARCHITECTURES.html
114
            _arches = _TORCH_CUDA_ARCH_LIST.replace(".", "").replace(" ", ";").split(";")
115
116
            _arches = [arch[:-4] if arch.endswith("+PTX") else f"{arch}-real" for arch in _arches]
            cmake_args += [f"-DCMAKE_CUDA_ARCHITECTURES={';'.join(_arches)}"]
moto's avatar
moto committed
117
118

        # Default to Ninja
119
        if "CMAKE_GENERATOR" not in os.environ or platform.system() == "Windows":
moto's avatar
moto committed
120
            cmake_args += ["-GNinja"]
121
        if platform.system() == "Windows":
122
            import sys
123

124
125
126
127
128
129
            python_version = sys.version_info
            cmake_args += [
                "-DCMAKE_C_COMPILER=cl",
                "-DCMAKE_CXX_COMPILER=cl",
                f"-DPYTHON_VERSION={python_version.major}.{python_version.minor}",
            ]
moto's avatar
moto committed
130
131
132
133
134
135
136
137
138
139
140
141
142

        # Set CMAKE_BUILD_PARALLEL_LEVEL to control the parallel build level
        # across all generators.
        if "CMAKE_BUILD_PARALLEL_LEVEL" not in os.environ:
            # self.parallel is a Python 3 only way to set parallel jobs by hand
            # using -j in the build_ext call, not supported by pip or PyPA-build.
            if hasattr(self, "parallel") and self.parallel:
                # CMake 3.12+ only.
                build_args += ["-j{}".format(self.parallel)]

        if not os.path.exists(self.build_temp):
            os.makedirs(self.build_temp)

143
144
        subprocess.check_call(["cmake", str(_ROOT_DIR)] + cmake_args, cwd=self.build_temp)
        subprocess.check_call(["cmake", "--build", "."] + build_args, cwd=self.build_temp)
moto's avatar
moto committed
145
146
147

    def get_ext_filename(self, fullname):
        ext_filename = super().get_ext_filename(fullname)
148
        ext_filename_parts = ext_filename.split(".")
moto's avatar
moto committed
149
        without_abi = ext_filename_parts[:-2] + ext_filename_parts[-1:]
150
        ext_filename = ".".join(without_abi)
moto's avatar
moto committed
151
        return ext_filename