setup.py 7.58 KB
Newer Older
facebook-github-bot's avatar
facebook-github-bot committed
1
#!/usr/bin/env python
2
# Copyright (c) Meta Platforms, Inc. and affiliates.
Patrick Labatut's avatar
Patrick Labatut committed
3
4
5
6
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
facebook-github-bot's avatar
facebook-github-bot committed
7
8
9

import glob
import os
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
10
import runpy
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
11
import sys
Christoph Lassner's avatar
Christoph Lassner committed
12
import warnings
13
from typing import List, Optional
14

facebook-github-bot's avatar
facebook-github-bot committed
15
import torch
16
from setuptools import find_packages, setup
17
from torch.utils.cpp_extension import CppExtension, CUDA_HOME, CUDAExtension
facebook-github-bot's avatar
facebook-github-bot committed
18
19


20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
def get_existing_ccbin(nvcc_args: List[str]) -> Optional[str]:
    """
    Given a list of nvcc arguments, return the compiler if specified.

    Note from CUDA doc: Single value options and list options must have
    arguments, which must follow the name of the option itself by either
    one of more spaces or an equals character.
    """
    last_arg = None
    for arg in reversed(nvcc_args):
        if arg == "-ccbin":
            return last_arg
        if arg.startswith("-ccbin="):
            return arg[7:]
        last_arg = arg
    return None


facebook-github-bot's avatar
facebook-github-bot committed
38
def get_extensions():
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
39
40
41
42
43
44
45
    no_extension = os.getenv("PYTORCH3D_NO_EXTENSION", "0") == "1"
    if no_extension:
        msg = "SKIPPING EXTENSION BUILD. PYTORCH3D WILL NOT WORK!"
        print(msg, file=sys.stderr)
        warnings.warn(msg)
        return []

facebook-github-bot's avatar
facebook-github-bot committed
46
47
    this_dir = os.path.dirname(os.path.abspath(__file__))
    extensions_dir = os.path.join(this_dir, "pytorch3d", "csrc")
48
49
    sources = glob.glob(os.path.join(extensions_dir, "**", "*.cpp"), recursive=True)
    source_cuda = glob.glob(os.path.join(extensions_dir, "**", "*.cu"), recursive=True)
facebook-github-bot's avatar
facebook-github-bot committed
50
51
    extension = CppExtension

52
    extra_compile_args = {"cxx": ["-std=c++17"]}
facebook-github-bot's avatar
facebook-github-bot committed
53
    define_macros = []
54
    include_dirs = [extensions_dir]
facebook-github-bot's avatar
facebook-github-bot committed
55

56
    force_cuda = os.getenv("FORCE_CUDA", "0") == "1"
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
57
58
59
60
    force_no_cuda = os.getenv("PYTORCH3D_FORCE_NO_CUDA", "0") == "1"
    if (
        not force_no_cuda and torch.cuda.is_available() and CUDA_HOME is not None
    ) or force_cuda:
facebook-github-bot's avatar
facebook-github-bot committed
61
62
63
        extension = CUDAExtension
        sources += source_cuda
        define_macros += [("WITH_CUDA", None)]
64
65
66
67
68
        # Thrust is only used for its tuple objects.
        # With CUDA 11.0 we can't use the cudatoolkit's version of cub.
        # We take the risk that CUB and Thrust are incompatible, because
        # we aren't using parts of Thrust which actually use CUB.
        define_macros += [("THRUST_IGNORE_CUB_VERSION_CHECK", None)]
69
        cub_home = os.environ.get("CUB_HOME", None)
70
        nvcc_args = [
facebook-github-bot's avatar
facebook-github-bot committed
71
72
73
74
75
            "-DCUDA_HAS_FP16=1",
            "-D__CUDA_NO_HALF_OPERATORS__",
            "-D__CUDA_NO_HALF_CONVERSIONS__",
            "-D__CUDA_NO_HALF2_OPERATORS__",
        ]
76
        if os.name != "nt":
77
            nvcc_args.append("-std=c++17")
78
79
80
81
82
        if cub_home is None:
            prefix = os.environ.get("CONDA_PREFIX", None)
            if prefix is not None and os.path.isdir(prefix + "/include/cub"):
                cub_home = prefix + "/include"

Christoph Lassner's avatar
Christoph Lassner committed
83
84
85
86
87
88
89
90
91
        if cub_home is None:
            warnings.warn(
                "The environment variable `CUB_HOME` was not found. "
                "NVIDIA CUB is required for compilation and can be downloaded "
                "from `https://github.com/NVIDIA/cub/releases`. You can unpack "
                "it to a location of your choice and set the environment variable "
                "`CUB_HOME` to the folder containing the `CMakeListst.txt` file."
            )
        else:
92
            include_dirs.append(os.path.realpath(cub_home).replace("\\ ", " "))
93
94
95
        nvcc_flags_env = os.getenv("NVCC_FLAGS", "")
        if nvcc_flags_env != "":
            nvcc_args.extend(nvcc_flags_env.split(" "))
facebook-github-bot's avatar
facebook-github-bot committed
96

97
98
        # This is needed for pytorch 1.6 and earlier. See e.g.
        # https://github.com/facebookresearch/pytorch3d/issues/436
99
100
101
102
103
104
105
106
107
108
109
110
        # It is harmless after https://github.com/pytorch/pytorch/pull/47404 .
        # But it can be problematic in torch 1.7.0 and 1.7.1
        if torch.__version__[:4] != "1.7.":
            CC = os.environ.get("CC", None)
            if CC is not None:
                existing_CC = get_existing_ccbin(nvcc_args)
                if existing_CC is None:
                    CC_arg = "-ccbin={}".format(CC)
                    nvcc_args.append(CC_arg)
                elif existing_CC != CC:
                    msg = f"Inconsistent ccbins: {CC} and {existing_CC}"
                    raise ValueError(msg)
111
112

        extra_compile_args["nvcc"] = nvcc_args
facebook-github-bot's avatar
facebook-github-bot committed
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128

    sources = [os.path.join(extensions_dir, s) for s in sources]

    ext_modules = [
        extension(
            "pytorch3d._C",
            sources,
            include_dirs=include_dirs,
            define_macros=define_macros,
            extra_compile_args=extra_compile_args,
        )
    ]

    return ext_modules


129
# Retrieve __version__ from the package.
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
130
__version__ = runpy.run_path("pytorch3d/__init__.py")["__version__"]
sangwz's avatar
sangwz committed
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
import subprocess
def get_abi():
    try:
        command = "echo '#include <string>' | gcc -x c++ -E -dM - | fgrep _GLIBCXX_USE_CXX11_ABI"
        result = subprocess.run(command, shell=True, capture_output=True, text=True)
        output = result.stdout.strip()
        abi = "abi" + output.split(" ")[-1]
        return abi
    except Exception:
        return 'abiUnknown'
dcu_version = __version__
dcu_version += '+das1.1'
sha = "Unknown"
cwd = os.path.dirname(os.path.abspath(__file__))
try:
    sha = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=cwd).decode("ascii").strip()
except Exception:
    pass

if sha != 'Unknown':
    dcu_version += '.git' + sha[:7]
dcu_version += "." + get_abi()
if os.getenv("ROCM_PATH"):
    rocm_path = os.getenv('ROCM_PATH', "")
    rocm_version_path = os.path.join(rocm_path, '.info', "rocm_version")
    with open(rocm_version_path, 'r',encoding='utf-8') as file:
        lines = file.readlines()
    rocm_version=lines[0][:-2].replace(".", "")
    dcu_version += ".dtk" + rocm_version
# torch version
import torch
dcu_version += ".torch" + torch.__version__[:]
def write_version_file():
    cwd = os.path.dirname(os.path.abspath(__file__))
    version_path = os.path.join(cwd, "pytorch3d", "__init__.py")
    with open(version_path, "a") as f:
        f.write(f"\n__dcu_version__ = '{dcu_version}'")
168
169
170
171
172
173
174
175
176
177

if os.getenv("PYTORCH3D_NO_NINJA", "0") == "1":

    class BuildExtension(torch.utils.cpp_extension.BuildExtension):
        def __init__(self, *args, **kwargs):
            super().__init__(use_ninja=False, *args, **kwargs)

else:
    BuildExtension = torch.utils.cpp_extension.BuildExtension

178
trainer = "pytorch3d.implicitron_trainer"
179

sangwz's avatar
sangwz committed
180
181
write_version_file()

facebook-github-bot's avatar
facebook-github-bot committed
182
183
setup(
    name="pytorch3d",
sangwz's avatar
sangwz committed
184
    version=dcu_version,
facebook-github-bot's avatar
facebook-github-bot committed
185
186
    author="FAIR",
    url="https://github.com/facebookresearch/pytorch3d",
187
    description="PyTorch3D is FAIR's library of reusable components "
facebook-github-bot's avatar
facebook-github-bot committed
188
    "for deep Learning with 3D data.",
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
189
    packages=find_packages(
190
191
192
193
        exclude=("configs", "tests", "tests.*", "docs.*", "projects.*")
    )
    + [trainer],
    package_dir={trainer: "projects/implicitron_trainer"},
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
194
    install_requires=["fvcore", "iopath"],
facebook-github-bot's avatar
facebook-github-bot committed
195
196
    extras_require={
        "all": ["matplotlib", "tqdm>4.29.0", "imageio", "ipywidgets"],
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
197
198
199
200
201
202
203
204
        "dev": ["flake8", "usort"],
        "implicitron": [
            "hydra-core>=1.1",
            "visdom",
            "lpips",
            "tqdm>4.29.0",
            "matplotlib",
            "accelerate",
Roman Shapovalov's avatar
Roman Shapovalov committed
205
            "sqlalchemy>=2.0",
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
206
        ],
207
208
209
    },
    entry_points={
        "console_scripts": [
210
211
            f"pytorch3d_implicitron_runner={trainer}.experiment:experiment",
            f"pytorch3d_implicitron_visualizer={trainer}.visualize_reconstruction:main",
212
        ]
facebook-github-bot's avatar
facebook-github-bot committed
213
214
    },
    ext_modules=get_extensions(),
215
    cmdclass={"build_ext": BuildExtension},
216
217
218
    package_data={
        "": ["*.json"],
    },
facebook-github-bot's avatar
facebook-github-bot committed
219
)