Skip to content

Commit 77d4816

Browse files
committed
Switch to cmake for build
1 parent f5aced8 commit 77d4816

File tree

15 files changed

+389
-198
lines changed

15 files changed

+389
-198
lines changed

.circleci/config.yml

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,8 +42,8 @@ commands:
4242
description: "installs tools required to build torchaudio"
4343
steps:
4444
- run:
45-
name: Install cmake and pkg-config
46-
command: HOMEBREW_NO_AUTO_UPDATE=1 brew install cmake pkg-config wget
45+
name: Install pkg-config
46+
command: HOMEBREW_NO_AUTO_UPDATE=1 brew install pkg-config wget
4747
# Disable brew auto update which is very slow
4848

4949
binary_common: &binary_common
@@ -430,7 +430,7 @@ jobs:
430430
resource_class: gpu.small
431431
environment:
432432
<<: *environment
433-
image_name: "pytorch/torchaudio_unittest_base:manylinux-cuda10.1"
433+
image_name: pytorch/torchaudio_unittest_base:manylinux-cuda10.1-cudnn7-20201203
434434
steps:
435435
- checkout
436436
- attach_workspace:

.circleci/config.yml.in

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,8 +42,8 @@ commands:
4242
description: "installs tools required to build torchaudio"
4343
steps:
4444
- run:
45-
name: Install cmake and pkg-config
46-
command: HOMEBREW_NO_AUTO_UPDATE=1 brew install cmake pkg-config wget
45+
name: Install pkg-config
46+
command: HOMEBREW_NO_AUTO_UPDATE=1 brew install pkg-config wget
4747
# Disable brew auto update which is very slow
4848

4949
binary_common: &binary_common
@@ -430,7 +430,7 @@ jobs:
430430
resource_class: gpu.small
431431
environment:
432432
<<: *environment
433-
image_name: "pytorch/torchaudio_unittest_base:manylinux-cuda10.1"
433+
image_name: pytorch/torchaudio_unittest_base:manylinux-cuda10.1-cudnn7-20201203
434434
steps:
435435
- checkout
436436
- attach_workspace:

.circleci/torchscript_bc_test/environment.yml

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,12 @@ dependencies:
77
- pytest
88
- pytest-cov
99
- codecov
10-
- librosa
10+
- librosa>=0.8.0
1111
- llvmlite==0.31 # See https://github.com/pytorch/audio/pull/766
1212
- pip
1313
- pip:
14+
- cmake
15+
- ninja
1416
- kaldi-io
1517
- scipy
1618
- parameterized

.circleci/unittest/linux/docker/build_and_push.sh

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,15 +7,14 @@ if [ $# -ne 1 ]; then
77
exit 1
88
fi
99

10+
datestr="$(date "+%Y%m%d")"
1011
if [ "$1" = "cpu" ]; then
1112
base_image="ubuntu:18.04"
12-
image="pytorch/torchaudio_unittest_base:manylinux"
13-
elif [[ "$1" =~ ^(9.2|10.1)$ ]]; then
14-
base_image="nvidia/cuda:$1-runtime-ubuntu18.04"
15-
image="pytorch/torchaudio_unittest_base:manylinux-cuda$1"
13+
image="pytorch/torchaudio_unittest_base:manylinux-${datestr}"
1614
else
17-
printf "Unexpected <CUDA_VERSION> string: %s" "$1"
18-
exit 1;
15+
base_image="nvidia/cuda:$1-devel-ubuntu18.04"
16+
docker pull "${base_image}"
17+
image="pytorch/torchaudio_unittest_base:manylinux-cuda$1-${datestr}"
1918
fi
2019

2120
cd "$( dirname "${BASH_SOURCE[0]}" )"

.circleci/unittest/linux/scripts/install.sh

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ conda install -y -c "pytorch-${UPLOAD_CHANNEL}" pytorch ${cudatoolkit}
3838

3939
# 2. Install torchaudio
4040
printf "* Installing torchaudio\n"
41+
git submodule update --init --recursive
4142
BUILD_TRANSDUCER=1 BUILD_SOX=1 python setup.py install
4243

4344
# 3. Install Test tools

.circleci/unittest/linux/scripts/setup_env.sh

Lines changed: 1 addition & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
#
66
# Do not install PyTorch and torchaudio here, otherwise they also get cached.
77

8-
set -e
8+
set -ex
99

1010
root_dir="$(git rev-parse --show-toplevel)"
1111
conda_dir="${root_dir}/conda"
@@ -41,12 +41,3 @@ conda activate "${env_dir}"
4141

4242
# 3. Install minimal build tools
4343
pip --quiet install cmake ninja
44-
45-
# 4. Buld codecs
46-
git submodule update --init --recursive
47-
mkdir -p third_party/build
48-
(
49-
cd third_party/build
50-
cmake -GNinja ..
51-
cmake --build .
52-
)

CMakeLists.txt

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
cmake_minimum_required(VERSION 3.5 FATAL_ERROR)
2+
3+
# Most of the configurations are taken from PyTorch
4+
# https://github.com/pytorch/pytorch/blob/0c9fb4aff0d60eaadb04e4d5d099fb1e1d5701a9/CMakeLists.txt
5+
6+
# Use compiler ID "AppleClang" instead of "Clang" for XCode.
7+
# Not setting this sometimes makes XCode C compiler gets detected as "Clang",
8+
# even when the C++ one is detected as "AppleClang".
9+
cmake_policy(SET CMP0010 NEW)
10+
cmake_policy(SET CMP0025 NEW)
11+
12+
# Suppress warning flags in default MSVC configuration. It's not
13+
# mandatory that we do this (and we don't if cmake is old), but it's
14+
# nice when it's possible, and it's possible on our Windows configs.
15+
if(NOT CMAKE_VERSION VERSION_LESS 3.15.0)
16+
cmake_policy(SET CMP0092 NEW)
17+
endif()
18+
19+
project(torchaudio)
20+
21+
# check and set CMAKE_CXX_STANDARD
22+
string(FIND "${CMAKE_CXX_FLAGS}" "-std=c++" env_cxx_standard)
23+
if(env_cxx_standard GREATER -1)
24+
message(
25+
WARNING "C++ standard version definition detected in environment variable."
26+
"PyTorch requires -std=c++14. Please remove -std=c++ settings in your environment.")
27+
endif()
28+
set(CMAKE_CXX_STANDARD 14)
29+
set(CMAKE_C_STANDARD 11)
30+
31+
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
32+
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
33+
34+
# Apple specific
35+
if(APPLE)
36+
# Get clang version on macOS
37+
execute_process( COMMAND ${CMAKE_CXX_COMPILER} --version OUTPUT_VARIABLE clang_full_version_string )
38+
string(REGEX REPLACE "Apple LLVM version ([0-9]+\\.[0-9]+).*" "\\1" CLANG_VERSION_STRING ${clang_full_version_string})
39+
message( STATUS "CLANG_VERSION_STRING: " ${CLANG_VERSION_STRING} )
40+
41+
# RPATH stuff
42+
set(CMAKE_MACOSX_RPATH ON)
43+
44+
set(CMAKE_SHARED_LIBRARY_SUFFIX ".so")
45+
endif()
46+
47+
48+
# Options
49+
option(BUILD_SOX "Build libsox statically" OFF)
50+
option(BUILD_TRANSDUCER "Enable transducer" OFF)
51+
option(BUILD_LIBTORCHAUDIO "Build C++ Library" ON)
52+
option(BUILD_PYTHON_EXTENSION "Build Python extension" OFF)
53+
54+
find_package(Torch REQUIRED)
55+
56+
# Set -D_GLIBCXX_USE_CXX11_ABI for third party builds
57+
set(CMAKE_CXX_FLAGS "${CXXFLAGS} ${TORCH_CXX_FLAGS}")
58+
59+
add_subdirectory(third_party)
60+
add_subdirectory(torchaudio/csrc)

build_tools/setup_helpers/extension.py

Lines changed: 68 additions & 132 deletions
Original file line numberDiff line numberDiff line change
@@ -2,23 +2,20 @@
22
import platform
33
import subprocess
44
from pathlib import Path
5+
import distutils.sysconfig
56

7+
from setuptools import Extension
8+
from setuptools.command.build_ext import build_ext
69
import torch
7-
from torch.utils.cpp_extension import (
8-
CppExtension,
9-
BuildExtension as TorchBuildExtension
10-
)
1110

1211
__all__ = [
1312
'get_ext_modules',
14-
'BuildExtension',
13+
'CMakeBuild',
1514
]
1615

1716
_THIS_DIR = Path(__file__).parent.resolve()
1817
_ROOT_DIR = _THIS_DIR.parent.parent.resolve()
19-
_CSRC_DIR = _ROOT_DIR / 'torchaudio' / 'csrc'
20-
_TP_BASE_DIR = _ROOT_DIR / 'third_party'
21-
_TP_INSTALL_DIR = _TP_BASE_DIR / 'install'
18+
_TORCHAUDIO_DIR = _ROOT_DIR / 'torchaudio'
2219

2320

2421
def _get_build(var):
@@ -38,132 +35,71 @@ def _get_build(var):
3835
_BUILD_TRANSDUCER = _get_build("BUILD_TRANSDUCER")
3936

4037

41-
def _get_eca(debug):
42-
eca = []
43-
if debug:
44-
eca += ["-O0", "-g"]
45-
else:
46-
eca += ["-O3"]
47-
if _BUILD_TRANSDUCER:
48-
eca += ['-DBUILD_TRANSDUCER']
49-
return eca
50-
51-
52-
def _get_ela(debug):
53-
ela = []
54-
if debug:
55-
if platform.system() == "Windows":
56-
ela += ["/DEBUG:FULL"]
57-
else:
58-
ela += ["-O0", "-g"]
59-
else:
60-
ela += ["-O3"]
61-
return ela
62-
63-
64-
def _get_srcs():
65-
srcs = [_CSRC_DIR / 'pybind.cpp']
66-
srcs += list(_CSRC_DIR.glob('sox/**/*.cpp'))
67-
if _BUILD_TRANSDUCER:
68-
srcs += [_CSRC_DIR / 'transducer.cpp']
69-
return [str(path) for path in srcs]
70-
71-
72-
def _get_include_dirs():
73-
dirs = [
74-
str(_ROOT_DIR),
75-
]
76-
if _BUILD_SOX or _BUILD_TRANSDUCER:
77-
dirs.append(str(_TP_INSTALL_DIR / 'include'))
78-
return dirs
79-
80-
81-
def _get_extra_objects():
82-
libs = []
83-
if _BUILD_SOX:
84-
# NOTE: The order of the library listed bellow matters.
85-
#
86-
# (the most important thing is that dependencies come after a library
87-
# e.g., sox comes first, flac/vorbis comes before ogg, and
88-
# vorbisenc/vorbisfile comes before vorbis
89-
libs += [
90-
'libsox.a',
91-
'libmad.a',
92-
'libFLAC.a',
93-
'libmp3lame.a',
94-
'libopusfile.a',
95-
'libopus.a',
96-
'libvorbisenc.a',
97-
'libvorbisfile.a',
98-
'libvorbis.a',
99-
'libogg.a',
100-
'libopencore-amrnb.a',
101-
'libopencore-amrwb.a',
102-
]
103-
if _BUILD_TRANSDUCER:
104-
libs += ['libwarprnnt.a']
105-
106-
return [str(_TP_INSTALL_DIR / 'lib' / lib) for lib in libs]
107-
108-
109-
def _get_libraries():
110-
return [] if _BUILD_SOX else ['sox']
111-
112-
113-
def _get_cxx11_abi():
114-
try:
115-
value = int(torch._C._GLIBCXX_USE_CXX11_ABI)
116-
except ImportError:
117-
value = 0
118-
return f'-D_GLIBCXX_USE_CXX11_ABI={value}'
119-
38+
def get_ext_modules():
39+
if platform.system() == 'Windows':
40+
return None
41+
return [Extension(name='torchaudio._torchaudio', sources=[])]
12042

121-
def _build_third_party(base_build_dir):
122-
build_dir = os.path.join(base_build_dir, 'third_party')
123-
os.makedirs(build_dir, exist_ok=True)
124-
subprocess.run(
125-
args=[
126-
'cmake',
127-
f"-DCMAKE_CXX_FLAGS='{_get_cxx11_abi()}'",
128-
'-DCMAKE_VERBOSE_MAKEFILE:BOOL=ON',
129-
f'-DCMAKE_INSTALL_PREFIX={_TP_INSTALL_DIR}',
130-
f'-DBUILD_SOX={"ON" if _BUILD_SOX else "OFF"}',
131-
f'-DBUILD_TRANSDUCER={"ON" if _BUILD_TRANSDUCER else "OFF"}',
132-
f'{_TP_BASE_DIR}'],
133-
cwd=build_dir,
134-
check=True,
135-
)
136-
command = ['cmake', '--build', '.']
137-
if _BUILD_TRANSDUCER:
138-
command += ['--target', 'install']
139-
subprocess.run(
140-
args=command,
141-
cwd=build_dir,
142-
check=True,
143-
)
14443

44+
# Based off of
45+
# https://github.com/pybind/cmake_example/blob/580c5fd29d4651db99d8874714b07c0c49a53f8a/setup.py
46+
class CMakeBuild(build_ext):
47+
def run(self):
48+
try:
49+
subprocess.check_output(['cmake', '--version'])
50+
except OSError:
51+
raise RuntimeError("CMake is not available.")
52+
super().run()
14553

146-
_EXT_NAME = 'torchaudio._torchaudio'
54+
def build_extension(self, ext):
55+
extdir = os.path.abspath(
56+
os.path.dirname(self.get_ext_fullpath(ext.name)))
57+
58+
# required for auto-detection of auxiliary "native" libs
59+
if not extdir.endswith(os.path.sep):
60+
extdir += os.path.sep
61+
62+
cfg = "Debug" if self.debug else "Release"
63+
64+
cmake_args = [
65+
f"-DCMAKE_LIBRARY_OUTPUT_DIRECTORY={extdir}",
66+
f"-DCMAKE_BUILD_TYPE={cfg}",
67+
f"-DCMAKE_PREFIX_PATH={torch.utils.cmake_prefix_path}",
68+
'-DCMAKE_VERBOSE_MAKEFILE=ON',
69+
f"-DPython_INCLUDE_DIR={distutils.sysconfig.get_python_inc()}",
70+
f"-DBUILD_SOX:BOOL={'ON' if _BUILD_SOX else 'OFF'}",
71+
f"-DBUILD_TRANSDUCER:BOOL={'ON' if _BUILD_TRANSDUCER else 'OFF'}",
72+
"-DBUILD_PYTHON_EXTENSION:BOOL=ON",
73+
"-DBUILD_LIBTORCHAUDIO:BOOL=OFF",
74+
]
75+
build_args = [
14776

77+
]
14878

149-
def get_ext_modules(debug=False):
150-
if platform.system() == 'Windows':
151-
return None
152-
return [
153-
CppExtension(
154-
_EXT_NAME,
155-
_get_srcs(),
156-
libraries=_get_libraries(),
157-
include_dirs=_get_include_dirs(),
158-
extra_compile_args=_get_eca(debug),
159-
extra_objects=_get_extra_objects(),
160-
extra_link_args=_get_ela(debug),
161-
),
162-
]
163-
164-
165-
class BuildExtension(TorchBuildExtension):
166-
def build_extension(self, ext):
167-
if ext.name == _EXT_NAME and _BUILD_SOX:
168-
_build_third_party(self.build_temp)
169-
super().build_extension(ext)
79+
# Default to Ninja
80+
if 'CMAKE_GENERATOR' not in os.environ:
81+
cmake_args += ["-GNinja"]
82+
83+
# Set CMAKE_BUILD_PARALLEL_LEVEL to control the parallel build level
84+
# across all generators.
85+
if "CMAKE_BUILD_PARALLEL_LEVEL" not in os.environ:
86+
# self.parallel is a Python 3 only way to set parallel jobs by hand
87+
# using -j in the build_ext call, not supported by pip or PyPA-build.
88+
if hasattr(self, "parallel") and self.parallel:
89+
# CMake 3.12+ only.
90+
build_args += ["-j{}".format(self.parallel)]
91+
92+
if not os.path.exists(self.build_temp):
93+
os.makedirs(self.build_temp)
94+
95+
subprocess.check_call(
96+
["cmake", str(_ROOT_DIR)] + cmake_args, cwd=self.build_temp)
97+
subprocess.check_call(
98+
["cmake", "--build", "."] + build_args, cwd=self.build_temp)
99+
100+
def get_ext_filename(self, fullname):
101+
ext_filename = super().get_ext_filename(fullname)
102+
ext_filename_parts = ext_filename.split('.')
103+
without_abi = ext_filename_parts[:-2] + ext_filename_parts[-1:]
104+
ext_filename = '.'.join(without_abi)
105+
return ext_filename

packaging/build_wheel.sh

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ export BUILD_TYPE="wheel"
88
export NO_CUDA_PACKAGE=1
99
setup_env 0.8.0
1010
setup_wheel_python
11-
pip_install numpy future
11+
pip_install numpy future cmake ninja
1212
setup_pip_pytorch_version
1313
python setup.py clean
1414
if [[ "$OSTYPE" == "msys" ]]; then

0 commit comments

Comments
 (0)