setup.py 52.0 KB
Newer Older
R
risemeup1 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# 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 errno
import fnmatch
import glob
import multiprocessing
import os
import platform
import re
import shutil
import subprocess
import sys
from contextlib import contextmanager
from distutils.spawn import find_executable
from subprocess import CalledProcessError

R
risemeup1 已提交
29
from setuptools import Command, Extension, setup
30
from setuptools.command.develop import develop as DevelopCommandBase
R
risemeup1 已提交
31 32 33
from setuptools.command.egg_info import egg_info
from setuptools.command.install import install as InstallCommandBase
from setuptools.command.install_lib import install_lib
T
tianshuo78520a 已提交
34
from setuptools.dist import Distribution
R
risemeup1 已提交
35 36 37 38 39 40 41 42 43 44 45

if sys.version_info < (3, 7):
    raise RuntimeError(
        "Paddle only supports Python version>=3.7 now, you are using Python %s"
        % platform.python_version()
    )
else:
    if os.getenv("PY_VERSION") is None:
        print("export PY_VERSION = %s" % platform.python_version())
        python_version = platform.python_version()
        os.environ["PY_VERSION"] = python_version
46
    else:
Y
YUNSHEN XIE 已提交
47 48 49
        if os.getenv("PY_VERSION") != str(sys.version_info.major) + '.' + str(
            sys.version_info.minor
        ):
50 51
            raise RuntimeError(
                "You set PY_VERSION=%s, but your current python environment is %s, you should keep them consistent!"
Y
YUNSHEN XIE 已提交
52 53 54 55 56 57
                % (
                    os.getenv("PY_VERSION"),
                    str(sys.version_info.major)
                    + '.'
                    + str(sys.version_info.minor),
                )
58
            )
R
risemeup1 已提交
59 60 61 62 63 64 65

# check cmake
CMAKE = find_executable('cmake3') or find_executable('cmake')
assert (
    CMAKE
), 'The "cmake" executable is not found. Please check if Cmake is installed.'

66

R
risemeup1 已提交
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
TOP_DIR = os.path.dirname(os.path.realpath(__file__))

IS_WINDOWS = os.name == 'nt'


def filter_setup_args(input_args):
    cmake_and_build = True
    only_cmake = False
    rerun_cmake = False
    filter_args_list = []
    for arg in input_args:
        if arg == 'rerun-cmake':
            rerun_cmake = True  # delete Cmakecache.txt and rerun cmake
            continue
        if arg == 'only-cmake':
            only_cmake = True  # only cmake and do not make, leave a chance for users to adjust build options
            continue
        if arg in ['clean', 'egg_info', 'sdist']:
            cmake_and_build = False
        filter_args_list.append(arg)
    return cmake_and_build, only_cmake, rerun_cmake, filter_args_list


cmake_and_build, only_cmake, rerun_cmake, filter_args_list = filter_setup_args(
    sys.argv
)


def parse_input_command(input_parameters):
    dist = Distribution()
    # get script name :setup.py
    sys.argv = input_parameters
    dist.script_name = os.path.basename(sys.argv[0])
    # get args of setup.py
    dist.script_args = sys.argv[1:]
    print(
        "Start executing python {} {}".format(
            dist.script_name, "".join(dist.script_args)
        )
    )
    try:
        dist.parse_command_line()
    except:
        print(
            "An error occurred while parsing the parameters, '%s'"
            % dist.script_args
        )
        sys.exit(1)


class BinaryDistribution(Distribution):
    def has_ext_modules(foo):
        return True


RC = 0
ext_suffix = (
    '.dll'
    if os.name == 'nt'
    else ('.dylib' if sys.platform == 'darwin' else '.so')
)


def get_header_install_dir(header):
    if 'pb.h' in header:
        install_dir = re.sub(
            env_dict.get("PADDLE_BINARY_DIR") + '/', '', header
        )
    elif 'third_party' not in header:
        # paddle headers
        install_dir = re.sub(
            env_dict.get("PADDLE_SOURCE_DIR") + '/', '', header
        )
        print('install_dir: ', install_dir)
        if 'fluid/jit' in install_dir:
            install_dir = re.sub('fluid/jit', 'jit', install_dir)
            print('fluid/jit install_dir: ', install_dir)
    else:
        # third_party
        install_dir = re.sub(
147
            env_dict.get("THIRD_PARTY_PATH"), 'third_party', header
R
risemeup1 已提交
148
        )
149
        patterns = [
150 151
            'install/mkldnn/include/',
            'pybind/src/extern_pybind/include/',
152
            'third_party/xpu/src/extern_xpu/xpu/include/',
153
        ]
R
risemeup1 已提交
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 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
        for pattern in patterns:
            install_dir = re.sub(pattern, '', install_dir)
    return install_dir


class InstallHeaders(Command):
    """Override how headers are copied."""

    description = 'install C/C++ header files'

    user_options = [
        ('install-dir=', 'd', 'directory to install header files to'),
        ('force', 'f', 'force installation (overwrite existing files)'),
    ]

    boolean_options = ['force']

    def initialize_options(self):
        self.install_dir = None
        self.force = 0
        self.outfiles = []

    def finalize_options(self):
        self.set_undefined_options(
            'install', ('install_headers', 'install_dir'), ('force', 'force')
        )

    def run(self):
        hdrs = self.distribution.headers
        if not hdrs:
            return
        self.mkpath(self.install_dir)
        for header in hdrs:
            install_dir = get_header_install_dir(header)
            install_dir = os.path.join(
                self.install_dir, os.path.dirname(install_dir)
            )
            if not os.path.exists(install_dir):
                self.mkpath(install_dir)
            (out, _) = self.copy_file(header, install_dir)
            self.outfiles.append(out)
            # (out, _) = self.mkdir_and_copy_file(header)
            # self.outfiles.append(out)

    def get_inputs(self):
        return self.distribution.headers or []

    def get_outputs(self):
        return self.outfiles


class InstallCommand(InstallCommandBase):
    def finalize_options(self):

        ret = InstallCommandBase.finalize_options(self)
        self.install_lib = self.install_platlib
        print("install_lib:", self.install_platlib)

        self.install_headers = os.path.join(
            self.install_platlib, 'paddle', 'include'
        )
        print("install_headers:", self.install_headers)
        return ret


219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
class DevelopCommand(DevelopCommandBase):
    def run(self):
        # copy proto and .so to python_source_dir
        fluid_proto_binary_path = (
            paddle_binary_dir + '/python/paddle/fluid/proto/'
        )
        fluid_proto_source_path = (
            paddle_source_dir + '/python/paddle/fluid/proto/'
        )
        distributed_proto_binary_path = (
            paddle_binary_dir + '/python/paddle/distributed/fleet/proto/'
        )
        distributed_proto_source_path = (
            paddle_source_dir + '/python/paddle/distributed/fleet/proto/'
        )
234
        os.system(f"rm -rf {fluid_proto_source_path}")
235
        shutil.copytree(fluid_proto_binary_path, fluid_proto_source_path)
236
        os.system(f"rm -rf {distributed_proto_source_path}")
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
        shutil.copytree(
            distributed_proto_binary_path, distributed_proto_source_path
        )
        shutil.copy(
            paddle_binary_dir + '/python/paddle/fluid/libpaddle.so',
            paddle_source_dir + '/python/paddle/fluid/',
        )
        dynamic_library_binary_path = paddle_binary_dir + '/python/paddle/libs/'
        dynamic_library_source_path = paddle_source_dir + '/python/paddle/libs/'
        for lib_so in os.listdir(dynamic_library_binary_path):
            shutil.copy(
                dynamic_library_binary_path + lib_so,
                dynamic_library_source_path,
            )
        # write version.py and cuda_env_config_py to python_source_dir
        write_version_py(
            filename='{}/python/paddle/version/__init__.py'.format(
                paddle_source_dir
            )
        )
        write_cuda_env_config_py(
258
            filename=f'{paddle_source_dir}/python/paddle/cuda_env.py'
259 260 261 262 263 264 265 266 267
        )
        write_parameter_server_version_py(
            filename='{}/python/paddle/incubate/distributed/fleet/parameter_server/version.py'.format(
                paddle_source_dir
            )
        )
        DevelopCommandBase.run(self)


R
risemeup1 已提交
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
class EggInfo(egg_info):
    """Copy license file into `.dist-info` folder."""

    def run(self):
        # don't duplicate license into `.dist-info` when building a distribution
        if not self.distribution.have_run.get('install', True):
            self.mkpath(self.egg_info)
            self.copy_file(
                env_dict.get("PADDLE_SOURCE_DIR") + "/LICENSE", self.egg_info
            )

        egg_info.run(self)


# class Installlib is rewritten to add header files to .egg/paddle
class InstallLib(install_lib):
    def run(self):
        self.build()
        outfiles = self.install()
        hrds = self.distribution.headers
        if not hrds:
            return
        for header in hrds:
            install_dir = get_header_install_dir(header)
            install_dir = os.path.join(
                self.install_dir, 'paddle/include', os.path.dirname(install_dir)
            )
            if not os.path.exists(install_dir):
                self.mkpath(install_dir)
            self.copy_file(header, install_dir)
        if outfiles is not None:
            # always compile, in case we have any extension stubs to deal with
            self.byte_compile(outfiles)


def git_commit():
    try:
        cmd = ['git', 'rev-parse', 'HEAD']
        git_commit = (
            subprocess.Popen(
                cmd,
                stdout=subprocess.PIPE,
                cwd=env_dict.get("PADDLE_SOURCE_DIR"),
            )
            .communicate()[0]
            .strip()
        )
    except:
        git_commit = 'Unknown'
    git_commit = git_commit.decode('utf-8')
    return str(git_commit)


def _get_version_detail(idx):
    assert (
        idx < 3
    ), "vesion info consists of %(major)d.%(minor)d.%(patch)d, \
        so detail index must less than 3"
    tag_version_regex = env_dict.get("TAG_VERSION_REGEX")
    paddle_version = env_dict.get("PADDLE_VERSION")
    if re.match(tag_version_regex, paddle_version):
        version_details = paddle_version.split('.')
        if len(version_details) >= 3:
            return version_details[idx]
    return 0


def _mkdir_p(dir_str):
    try:
        os.makedirs(dir_str)
    except OSError as e:
R
risemeup1 已提交
339
        raise RuntimeError("Failed to create build folder")
R
risemeup1 已提交
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385


def get_major():
    return int(_get_version_detail(0))


def get_minor():
    return int(_get_version_detail(1))


def get_patch():
    return str(_get_version_detail(2))


def get_cuda_version():
    with_gpu = env_dict.get("WITH_GPU")
    if with_gpu == 'ON':
        return env_dict.get("CUDA_VERSION")
    else:
        return 'False'


def get_cudnn_version():
    with_gpu = env_dict.get("WITH_GPU")
    if with_gpu == 'ON':
        temp_cudnn_version = ''
        cudnn_major_version = env_dict.get("CUDNN_MAJOR_VERSION")
        if cudnn_major_version:
            temp_cudnn_version += cudnn_major_version
            cudnn_minor_version = env_dict.get("CUDNN_MINOR_VERSION")
            if cudnn_minor_version:
                temp_cudnn_version = (
                    temp_cudnn_version + '.' + cudnn_minor_version
                )
                cudnn_patchlevel_version = env_dict.get(
                    "CUDNN_PATCHLEVEL_VERSION"
                )
                if cudnn_patchlevel_version:
                    temp_cudnn_version = (
                        temp_cudnn_version + '.' + cudnn_patchlevel_version
                    )
        return temp_cudnn_version
    else:
        return 'False'


386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
def get_xpu_version():
    with_xpu = env_dict.get("WITH_XPU")
    if with_xpu == 'ON':
        return env_dict.get("XPU_BASE_DATE")
    else:
        return 'False'


def get_xpu_xccl_version():
    with_xpu_xccl = env_dict.get("WITH_XPU_BKCL")
    if with_xpu_xccl == 'ON':
        return env_dict.get("XPU_XCCL_BASE_VERSION")
    else:
        return 'False'


R
risemeup1 已提交
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
def is_taged():
    try:
        cmd = [
            'git',
            'describe',
            '--exact-match',
            '--tags',
            'HEAD',
            '2>/dev/null',
        ]
        git_tag = (
            subprocess.Popen(
                cmd,
                stdout=subprocess.PIPE,
                cwd=env_dict.get("PADDLE_SOURCE_DIR"),
            )
            .communicate()[0]
            .strip()
        )
        git_tag = git_tag.decode()
    except:
        return False
    if str(git_tag).replace('v', '') == env_dict.get("PADDLE_VERSION"):
        return True
    else:
        return False


def write_version_py(filename='paddle/version/__init__.py'):
    cnt = '''# THIS FILE IS GENERATED FROM PADDLEPADDLE SETUP.PY
#
433 434 435 436 437 438 439 440 441 442 443 444 445 446
full_version     = '%(major)d.%(minor)d.%(patch)s'
major            = '%(major)d'
minor            = '%(minor)d'
patch            = '%(patch)s'
rc               = '%(rc)d'
cuda_version     = '%(cuda)s'
cudnn_version    = '%(cudnn)s'
xpu_version      = '%(xpu)s'
xpu_xccl_version = '%(xpu_xccl)s'
istaged          = %(istaged)s
commit           = '%(commit)s'
with_mkl         = '%(with_mkl)s'

__all__ = ['cuda', 'cudnn', 'show', 'xpu', 'xpu_xccl']
R
risemeup1 已提交
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468

def show():
    """Get the version of paddle if `paddle` package if tagged. Otherwise, output the corresponding commit id.

    Returns:
        If paddle package is not tagged, the commit-id of paddle will be output.
        Otherwise, the following information will be output.

        full_version: version of paddle

        major: the major version of paddle

        minor: the minor version of paddle

        patch: the patch level version of paddle

        rc: whether it's rc version

        cuda: the cuda version of package. It will return `False` if CPU version paddle package is installed

        cudnn: the cudnn version of package. It will return `False` if CPU version paddle package is installed

469 470 471 472
        xpu: the xpu version of package. It will return `False` if non-XPU version paddle package is installed

        xpu_xccl: the xpu xccl version of package. It will return `False` if non-XPU version paddle package is installed

R
risemeup1 已提交
473 474 475 476 477 478 479 480 481 482 483 484 485 486
    Examples:
        .. code-block:: python

            import paddle

            # Case 1: paddle is tagged with 2.2.0
            paddle.version.show()
            # full_version: 2.2.0
            # major: 2
            # minor: 2
            # patch: 0
            # rc: 0
            # cuda: '10.2'
            # cudnn: '7.6.5'
487 488
            # xpu: '20230114'
            # xpu_xccl: '1.0.7'
R
risemeup1 已提交
489 490 491 492 493 494

            # Case 2: paddle is not tagged
            paddle.version.show()
            # commit: cfa357e984bfd2ffa16820e354020529df434f7d
            # cuda: '10.2'
            # cudnn: '7.6.5'
495 496
            # xpu: '20230114'
            # xpu_xccl: '1.0.7'
R
risemeup1 已提交
497 498 499 500 501 502 503 504 505 506 507
    """
    if istaged:
        print('full_version:', full_version)
        print('major:', major)
        print('minor:', minor)
        print('patch:', patch)
        print('rc:', rc)
    else:
        print('commit:', commit)
    print('cuda:', cuda_version)
    print('cudnn:', cudnn_version)
508 509
    print('xpu:', xpu_version)
    print('xpu_xccl:', xpu_xccl_version)
R
risemeup1 已提交
510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546

def mkl():
    return with_mkl

def cuda():
    """Get cuda version of paddle package.

    Returns:
        string: Return the version information of cuda. If paddle package is CPU version, it will return False.

    Examples:
        .. code-block:: python

            import paddle

            paddle.version.cuda()
            # '10.2'

    """
    return cuda_version

def cudnn():
    """Get cudnn version of paddle package.

    Returns:
        string: Return the version information of cudnn. If paddle package is CPU version, it will return False.

    Examples:
        .. code-block:: python

            import paddle

            paddle.version.cudnn()
            # '7.6.5'

    """
    return cudnn_version
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580

def xpu():
    """Get xpu version of paddle package.

    Returns:
        string: Return the version information of xpu. If paddle package is non-XPU version, it will return False.

    Examples:
        .. code-block:: python

            import paddle

            paddle.version.xpu()
            # '20230114'

    """
    return xpu_version

def xpu_xccl():
    """Get xpu xccl version of paddle package.

    Returns:
        string: Return the version information of xpu xccl. If paddle package is non-XPU version, it will return False.

    Examples:
        .. code-block:: python

            import paddle

            paddle.version.xpu_xccl()
            # '1.0.7'

    """
    return xpu_xccl_version
R
risemeup1 已提交
581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602
'''
    commit = git_commit()

    dirname = os.path.dirname(filename)

    try:
        os.makedirs(dirname)
    except OSError as e:
        if e.errno != errno.EEXIST:
            raise

    with open(filename, 'w') as f:
        f.write(
            cnt
            % {
                'major': get_major(),
                'minor': get_minor(),
                'patch': get_patch(),
                'rc': RC,
                'version': env_dict.get("PADDLE_VERSION"),
                'cuda': get_cuda_version(),
                'cudnn': get_cudnn_version(),
603 604
                'xpu': get_xpu_version(),
                'xpu_xccl': get_xpu_xccl_version(),
R
risemeup1 已提交
605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625
                'commit': commit,
                'istaged': is_taged(),
                'with_mkl': env_dict.get("WITH_MKL"),
            }
        )


def write_cuda_env_config_py(filename='paddle/cuda_env.py'):
    cnt = ""
    if env_dict.get("JIT_RELEASE_WHL") == 'ON':
        cnt = '''# THIS FILE IS GENERATED FROM PADDLEPADDLE SETUP.PY
#
import os
os.environ['CUDA_CACHE_MAXSIZE'] = '805306368'
'''

    with open(filename, 'w') as f:
        f.write(cnt)


def write_parameter_server_version_py(
626
    filename='paddle/incubate/distributed/fleet/parameter_server/version.py',
R
risemeup1 已提交
627 628 629 630 631
):
    cnt = '''

# THIS FILE IS GENERATED FROM PADDLEPADDLE SETUP.PY

meteor135's avatar
meteor135 已提交
632
from paddle.incubate.distributed.fleet.base import Mode
R
risemeup1 已提交
633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669

BUILD_MODE=Mode.%(mode)s

def is_transpiler():
    return Mode.TRANSPILER == BUILD_MODE

'''

    dirname = os.path.dirname(filename)

    try:
        os.makedirs(dirname)
    except OSError as e:
        if e.errno != errno.EEXIST:
            raise
    with open(filename, 'w') as f:
        f.write(
            cnt
            % {
                'mode': 'PSLIB'
                if env_dict.get("WITH_PSLIB") == 'ON'
                else 'TRANSPILER'
            }
        )


def find_files(pattern, root, recursive=False):
    for dirpath, _, files in os.walk(root):
        for filename in fnmatch.filter(files, pattern):
            yield os.path.join(dirpath, filename)
        if not recursive:
            break


@contextmanager
def cd(path):
    if not os.path.isabs(path):
670
        raise RuntimeError(f'Can only cd to absolute path, got: {path}')
R
risemeup1 已提交
671 672 673 674 675 676 677 678 679 680 681
    orig_path = os.getcwd()
    os.chdir(path)
    try:
        yield
    finally:
        os.chdir(orig_path)


def options_process(args, build_options):
    for key, value in sorted(build_options.items()):
        if value is not None:
682
            args.append(f"-D{key}={value}")
R
risemeup1 已提交
683 684


R
risemeup1 已提交
685
def get_cmake_generator():
686 687
    if os.getenv("GENERATOR"):
        cmake_generator = os.getenv("GENERATOR")
R
risemeup1 已提交
688 689 690 691 692
    else:
        cmake_generator = "Unix Makefiles"
    return cmake_generator


693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722
def cmake_run(build_path):
    args = []
    env_var = os.environ.copy()  # get env variables
    paddle_build_options = {}
    other_options = {}
    other_options.update(
        {
            option: option
            for option in (
                "PYTHON_LIBRARY",
                "INFERENCE_DEMO_INSTALL_DIR",
                "ON_INFER",
                "PYTHON_EXECUTABLE",
                "TENSORRT_ROOT",
                "CUDA_ARCH_NAME",
                "CUDA_ARCH_BIN",
                "PYTHON_INCLUDE_DIR",
                "PYTHON_LIBRARIES",
                "PY_VERSION",
                "CUB_PATH",
                "NEW_RELEASE_PYPI",
                "CUDNN_ROOT",
                "THIRD_PARTY_PATH",
                "NOAVX_CORE_FILE",
                "LITE_GIT_TAG",
                "CUDA_TOOLKIT_ROOT_DIR",
                "NEW_RELEASE_JIT",
                "XPU_SDK_ROOT",
                "MSVC_STATIC_CRT",
                "NEW_RELEASE_ALL",
723
                "GENERATOR",
Y
YUNSHEN XIE 已提交
724
                "CINN_GIT_TAG",
725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742
            )
        }
    )
    # if environment variables which start with "WITH_" or "CMAKE_",put it into build_options
    for option_key, option_value in env_var.items():
        if option_key.startswith(("CMAKE_", "WITH_")):
            paddle_build_options[option_key] = option_value
        if option_key in other_options:
            if (
                option_key == 'PYTHON_EXECUTABLE'
                or option_key == 'PYTHON_LIBRARY'
                or option_key == 'PYTHON_LIBRARIES'
            ):
                key = option_key + ":FILEPATH"
                print(key)
            elif option_key == 'PYTHON_INCLUDE_DIR':
                key = option_key + ':PATH'
                print(key)
743 744
            elif option_key == 'GENERATOR':
                key = 'CMAKE_' + option_key
745 746 747 748
            else:
                key = other_options[option_key]
            if key not in paddle_build_options:
                paddle_build_options[key] = option_value
749

750 751
    options_process(args, paddle_build_options)
    print("args:", args)
R
risemeup1 已提交
752 753 754 755
    with cd(build_path):
        cmake_args = []
        cmake_args.append(CMAKE)
        cmake_args += args
R
risemeup1 已提交
756
        cmake_args.append('-DWITH_SETUP_INSTALL=ON')
R
risemeup1 已提交
757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773
        cmake_args.append(TOP_DIR)
        print("cmake_args:", cmake_args)
        subprocess.check_call(cmake_args)


def build_run(args, build_path, envrion_var):
    with cd(build_path):
        build_args = []
        build_args.append(CMAKE)
        build_args += args
        print(" ".join(build_args))
        try:
            subprocess.check_call(build_args, cwd=build_path, env=envrion_var)
        except (CalledProcessError, KeyboardInterrupt) as e:
            sys.exit(1)


R
risemeup1 已提交
774
def run_cmake_build(build_path):
R
risemeup1 已提交
775 776 777 778 779 780
    build_type = (
        os.getenv("CMAKE_BUILD_TYPE")
        if os.getenv("CMAKE_BUILD_TYPE") is not None
        else "release"
    )
    build_args = ["--build", ".", "--target", "install", "--config", build_type]
R
risemeup1 已提交
781 782 783 784 785 786
    max_jobs = os.getenv("MAX_JOBS")
    if max_jobs is not None:
        max_jobs = max_jobs or str(multiprocessing.cpu_count())

        build_args += ["--"]
        if IS_WINDOWS:
787
            build_args += [f"/p:CL_MPCount={max_jobs}"]
R
risemeup1 已提交
788 789 790 791 792 793 794 795
        else:
            build_args += ["-j", max_jobs]
    else:
        build_args += ["-j", str(multiprocessing.cpu_count())]
    environ_var = os.environ.copy()
    build_run(build_args, build_path, environ_var)


R
risemeup1 已提交
796 797
def build_steps():
    print('------- Building start ------')
R
risemeup1 已提交
798 799 800 801 802 803 804 805
    build_dir = os.getenv("BUILD_DIR")
    if build_dir is not None:
        build_dir = TOP_DIR + '/' + build_dir
    else:
        build_dir = TOP_DIR + '/build'
    if not os.path.exists(build_dir):
        _mkdir_p(build_dir)
    build_path = build_dir
R
risemeup1 已提交
806
    print("build_dir:", build_dir)
R
risemeup1 已提交
807 808 809 810 811
    # run cmake to generate native build files
    cmake_cache_file_path = os.path.join(build_path, "CMakeCache.txt")
    # if rerun_cmake is True,remove CMakeCache.txt and rerun camke
    if os.path.isfile(cmake_cache_file_path) and rerun_cmake is True:
        os.remove(cmake_cache_file_path)
R
risemeup1 已提交
812 813

    CMAKE_GENERATOR = get_cmake_generator()
814 815 816 817 818 819 820 821
    bool_ninja = CMAKE_GENERATOR == "Ninja"
    build_ninja_file_path = os.path.join(build_path, "build.ninja")
    if os.path.exists(cmake_cache_file_path) and not (
        bool_ninja and not os.path.exists(build_ninja_file_path)
    ):
        print("Do not need rerun camke, everything is ready, run build now")
    else:
        cmake_run(build_path)
R
risemeup1 已提交
822 823 824 825 826 827
    # make
    if only_cmake:
        print(
            "You have finished running cmake, the program exited,run 'ccmake build' to adjust build options and 'python setup.py install to build'"
        )
        sys.exit()
R
risemeup1 已提交
828
    run_cmake_build(build_path)
R
risemeup1 已提交
829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873


def get_setup_requires():
    with open(
        env_dict.get("PADDLE_SOURCE_DIR") + '/python/requirements.txt'
    ) as f:
        setup_requires = (
            f.read().splitlines()
        )  # Specify the dependencies to install
    if sys.version_info >= (3, 7):
        setup_requires_tmp = []
        for setup_requires_i in setup_requires:
            if (
                "<\"3.6\"" in setup_requires_i
                or "<=\"3.6\"" in setup_requires_i
                or "<\"3.5\"" in setup_requires_i
                or "<=\"3.5\"" in setup_requires_i
                or "<\"3.7\"" in setup_requires_i
            ):
                continue
            setup_requires_tmp += [setup_requires_i]
        setup_requires = setup_requires_tmp
        return setup_requires
    else:
        raise RuntimeError(
            "please check your python version,Paddle only support Python version>=3.7 now"
        )


def get_package_data_and_package_dir():
    if os.name != 'nt':
        package_data = {
            'paddle.fluid': [env_dict.get("FLUID_CORE_NAME") + '.so']
        }
    else:
        package_data = {
            'paddle.fluid': [
                env_dict.get("FLUID_CORE_NAME") + '.pyd',
                env_dict.get("FLUID_CORE_NAME") + '.lib',
            ]
        }
    package_data['paddle.fluid'] += [
        paddle_binary_dir + '/python/paddle/cost_model/static_op_benchmark.json'
    ]
    if 'develop' in sys.argv:
874
        package_dir = {'': 'python'}
R
risemeup1 已提交
875 876 877 878 879 880 881 882 883 884 885 886 887 888
    else:
        package_dir = {
            '': env_dict.get("PADDLE_BINARY_DIR") + '/python',
            'paddle.fluid.proto.profiler': env_dict.get("PADDLE_BINARY_DIR")
            + '/paddle/fluid/platform',
            'paddle.fluid.proto': env_dict.get("PADDLE_BINARY_DIR")
            + '/paddle/fluid/framework',
            'paddle.fluid': env_dict.get("PADDLE_BINARY_DIR")
            + '/python/paddle/fluid',
        }
    # put all thirdparty libraries in paddle.libs
    libs_path = paddle_binary_dir + '/python/paddle/libs'
    package_data['paddle.libs'] = []
    package_data['paddle.libs'] = [
H
Hui Zhang 已提交
889 890
        ('libwarpctc' if os.name != 'nt' else 'warpctc') + ext_suffix,
        ('libwarprnnt' if os.name != 'nt' else 'warprnnt') + ext_suffix,
R
risemeup1 已提交
891 892
    ]
    shutil.copy(env_dict.get("WARPCTC_LIBRARIES"), libs_path)
H
Hui Zhang 已提交
893
    shutil.copy(env_dict.get("WARPRNNT_LIBRARIES"), libs_path)
R
risemeup1 已提交
894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953
    package_data['paddle.libs'] += [
        os.path.basename(env_dict.get("LAPACK_LIB")),
        os.path.basename(env_dict.get("BLAS_LIB")),
        os.path.basename(env_dict.get("GFORTRAN_LIB")),
        os.path.basename(env_dict.get("GNU_RT_LIB_1")),
    ]
    shutil.copy(env_dict.get("BLAS_LIB"), libs_path)
    shutil.copy(env_dict.get("LAPACK_LIB"), libs_path)
    shutil.copy(env_dict.get("GFORTRAN_LIB"), libs_path)
    shutil.copy(env_dict.get("GNU_RT_LIB_1"), libs_path)
    if env_dict.get("WITH_CUDNN_DSO") == 'ON' and os.path.exists(
        env_dict.get("CUDNN_LIBRARY")
    ):
        package_data['paddle.libs'] += [
            os.path.basename(env_dict.get("CUDNN_LIBRARY"))
        ]
        shutil.copy(env_dict.get("CUDNN_LIBRARY"), libs_path)
        if (
            sys.platform.startswith("linux")
            and env_dict.get("CUDNN_MAJOR_VERSION") == '8'
        ):
            # libcudnn.so includes libcudnn_ops_infer.so, libcudnn_ops_train.so,
            # libcudnn_cnn_infer.so, libcudnn_cnn_train.so, libcudnn_adv_infer.so,
            # libcudnn_adv_train.so
            cudnn_lib_files = glob.glob(
                os.path.dirname(env_dict.get("CUDNN_LIBRARY"))
                + '/libcudnn_*so.8'
            )
            for cudnn_lib in cudnn_lib_files:
                if os.path.exists(cudnn_lib):
                    package_data['paddle.libs'] += [os.path.basename(cudnn_lib)]
                    shutil.copy(cudnn_lib, libs_path)
    if not sys.platform.startswith("linux"):
        package_data['paddle.libs'] += [
            os.path.basename(env_dict.get("GNU_RT_LIB_2"))
        ]
        shutil.copy(env_dict.get("GNU_RT_LIB_2"), libs_path)
    if env_dict.get("WITH_MKL") == 'ON':
        shutil.copy(env_dict.get("MKLML_SHARED_LIB"), libs_path)
        shutil.copy(env_dict.get("MKLML_SHARED_IOMP_LIB"), libs_path)
        package_data['paddle.libs'] += [
            ('libmklml_intel' if os.name != 'nt' else 'mklml') + ext_suffix,
            ('libiomp5' if os.name != 'nt' else 'libiomp5md') + ext_suffix,
        ]
    else:
        if os.name == 'nt':
            # copy the openblas.dll
            shutil.copy(env_dict.get("OPENBLAS_SHARED_LIB"), libs_path)
            package_data['paddle.libs'] += ['openblas' + ext_suffix]
        elif (
            os.name == 'posix'
            and platform.machine() == 'aarch64'
            and env_dict.get("OPENBLAS_LIB").endswith('so')
        ):
            # copy the libopenblas.so on linux+aarch64
            # special: libpaddle.so without avx depends on 'libopenblas.so.0', not 'libopenblas.so'
            if os.path.exists(env_dict.get("OPENBLAS_LIB") + '.0'):
                shutil.copy(env_dict.get("OPENBLAS_LIB") + '.0', libs_path)
                package_data['paddle.libs'] += ['libopenblas.so.0']

954 955 956 957 958
    if len(env_dict.get("FLASHATTN_LIBRARIES", "")) > 1:
        package_data['paddle.libs'] += [
            os.path.basename(env_dict.get("FLASHATTN_LIBRARIES"))
        ]
        shutil.copy(env_dict.get("FLASHATTN_LIBRARIES"), libs_path)
R
risemeup1 已提交
959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985
    if env_dict.get("WITH_LITE") == 'ON':
        shutil.copy(env_dict.get("LITE_SHARED_LIB"), libs_path)
        package_data['paddle.libs'] += [
            'libpaddle_full_api_shared' + ext_suffix
        ]
        if env_dict.get("LITE_WITH_NNADAPTER") == 'ON':
            shutil.copy(env_dict.get("LITE_NNADAPTER_LIB"), libs_path)
            package_data['paddle.libs'] += ['libnnadapter' + ext_suffix]
            if env_dict.get("NNADAPTER_WITH_HUAWEI_ASCEND_NPU") == 'ON':
                shutil.copy(env_dict.get("LITE_NNADAPTER_NPU_LIB"), libs_path)
                package_data['paddle.libs'] += [
                    'libnnadapter_driver_huawei_ascend_npu' + ext_suffix
                ]
    if env_dict.get("WITH_CINN") == 'ON':
        shutil.copy(
            env_dict.get("CINN_LIB_LOCATION")
            + '/'
            + env_dict.get("CINN_LIB_NAME"),
            libs_path,
        )
        shutil.copy(
            env_dict.get("CINN_INCLUDE_DIR")
            + '/cinn/runtime/cuda/cinn_cuda_runtime_source.cuh',
            libs_path,
        )
        package_data['paddle.libs'] += ['libcinnapi.so']
        package_data['paddle.libs'] += ['cinn_cuda_runtime_source.cuh']
986 987 988 989 990 991 992 993

        cinn_fp16_file = (
            env_dict.get("CINN_INCLUDE_DIR") + '/cinn/runtime/cuda/float16.h'
        )
        if os.path.exists(cinn_fp16_file):
            shutil.copy(cinn_fp16_file, libs_path)
            package_data['paddle.libs'] += ['float16.h']

R
risemeup1 已提交
994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
        if env_dict.get("CMAKE_BUILD_TYPE") == 'Release' and os.name != 'nt':
            command = (
                "patchelf --set-rpath '$ORIGIN/' %s/" % libs_path
                + env_dict.get("CINN_LIB_NAME")
            )
            if os.system(command) != 0:
                raise Exception(
                    'patch '
                    + libs_path
                    + '/'
                    + env_dict.get("CINN_LIB_NAME")
                    + ' failed',
                    'command: %s' % command,
                )
    if env_dict.get("WITH_PSLIB") == 'ON':
        shutil.copy(env_dict.get("PSLIB_LIB"), libs_path)
1010
        shutil.copy(env_dict.get("JVM_LIB"), libs_path)
R
risemeup1 已提交
1011 1012 1013 1014
        if os.path.exists(env_dict.get("PSLIB_VERSION_PY")):
            shutil.copy(
                env_dict.get("PSLIB_VERSION_PY"),
                paddle_binary_dir
1015
                + '/python/paddle/incubate/distributed/fleet/parameter_server/pslib/',
R
risemeup1 已提交
1016 1017
            )
        package_data['paddle.libs'] += ['libps' + ext_suffix]
1018
        package_data['paddle.libs'] += ['libjvm' + ext_suffix]
R
risemeup1 已提交
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
    if env_dict.get("WITH_MKLDNN") == 'ON':
        if env_dict.get("CMAKE_BUILD_TYPE") == 'Release' and os.name != 'nt':
            # only change rpath in Release mode.
            # TODO(typhoonzero): use install_name_tool to patch mkl libs once
            # we can support mkl on mac.
            #
            # change rpath of libdnnl.so.1, add $ORIGIN/ to it.
            # The reason is that all thirdparty libraries in the same directory,
            # thus, libdnnl.so.1 will find libmklml_intel.so and libiomp5.so.
            command = "patchelf --set-rpath '$ORIGIN/' " + env_dict.get(
                "MKLDNN_SHARED_LIB"
            )
            if os.system(command) != 0:
                raise Exception(
                    "patch libdnnl.so failed, command: %s" % command
                )
        shutil.copy(env_dict.get("MKLDNN_SHARED_LIB"), libs_path)
        if os.name != 'nt':
            shutil.copy(env_dict.get("MKLDNN_SHARED_LIB_1"), libs_path)
            shutil.copy(env_dict.get("MKLDNN_SHARED_LIB_2"), libs_path)
            package_data['paddle.libs'] += [
                'libmkldnn.so.0',
                'libdnnl.so.1',
                'libdnnl.so.2',
            ]
        else:
            package_data['paddle.libs'] += ['mkldnn.dll']

    if env_dict.get("WITH_ONNXRUNTIME") == 'ON':
        shutil.copy(env_dict.get("ONNXRUNTIME_SHARED_LIB"), libs_path)
        shutil.copy(env_dict.get("PADDLE2ONNX_LIB"), libs_path)
        if os.name == 'nt':
            package_data['paddle.libs'] += [
                'paddle2onnx.dll',
                'onnxruntime.dll',
            ]
        else:
            package_data['paddle.libs'] += [
                env_dict.get("PADDLE2ONNX_LIB_NAME"),
                env_dict.get("ONNXRUNTIME_LIB_NAME"),
            ]

    if env_dict.get("WITH_XPU") == 'ON':
        # only change rpath in Release mode,
        if env_dict.get("CMAKE_BUILD_TYPE") == 'Release':
            if os.name != 'nt':
                if env_dict.get("APPLE") == "1":
                    command = (
                        "install_name_tool -id \"@loader_path/\" "
                        + env_dict.get("XPU_API_LIB")
                    )
                else:
                    command = "patchelf --set-rpath '$ORIGIN/' " + env_dict.get(
                        "XPU_API_LIB"
                    )
                if os.system(command) != 0:
                    raise Exception(
                        'patch ' + env_dict.get("XPU_API_LIB") + 'failed ,',
                        "command: %s" % command,
                    )
        shutil.copy(env_dict.get("XPU_API_LIB"), libs_path)
R
risemeup1 已提交
1080 1081 1082 1083 1084
        package_data['paddle.libs'] += [env_dict.get("XPU_API_LIB_NAME")]
        xpu_rt_lib_list = glob.glob(env_dict.get("XPU_RT_LIB") + '*')
        for xpu_rt_lib_file in xpu_rt_lib_list:
            shutil.copy(xpu_rt_lib_file, libs_path)
            package_data['paddle.libs'] += [os.path.basename(xpu_rt_lib_file)]
R
risemeup1 已提交
1085 1086 1087 1088 1089

    if env_dict.get("WITH_XPU_BKCL") == 'ON':
        shutil.copy(env_dict.get("XPU_BKCL_LIB"), libs_path)
        package_data['paddle.libs'] += [env_dict.get("XPU_BKCL_LIB_NAME")]

1090 1091 1092
    if env_dict.get("WITH_XPU_XFT") == 'ON':
        shutil.copy(env_dict.get("XPU_XFT_LIB"), libs_path)
        package_data['paddle.libs'] += [env_dict.get("XPU_XFT_LIB_NAME")]
R
risemeup1 已提交
1093 1094 1095 1096 1097 1098
    # remove unused paddle/libs/__init__.py
    if os.path.isfile(libs_path + '/__init__.py'):
        os.remove(libs_path + '/__init__.py')
    package_dir['paddle.libs'] = libs_path

    # change rpath of ${FLUID_CORE_NAME}.ext, add $ORIGIN/../libs/ to it.
H
Hui Zhang 已提交
1099
    # The reason is that libwarpctc.ext, libwarprnnt.ext, libiomp5.ext etc are in paddle.libs, and
R
risemeup1 已提交
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153
    # ${FLUID_CORE_NAME}.ext is in paddle.fluid, thus paddle/fluid/../libs will pointer to above libraries.
    # This operation will fix https://github.com/PaddlePaddle/Paddle/issues/3213
    if env_dict.get("CMAKE_BUILD_TYPE") == 'Release':
        if os.name != 'nt':
            # only change rpath in Release mode, since in Debug mode, ${FLUID_CORE_NAME}.xx is too large to be changed.
            if env_dict.get("APPLE") == "1":
                commands = [
                    "install_name_tool -id '@loader_path/../libs/' "
                    + env_dict.get("PADDLE_BINARY_DIR")
                    + '/python/paddle/fluid/'
                    + env_dict.get("FLUID_CORE_NAME")
                    + '.so'
                ]
                commands.append(
                    "install_name_tool -add_rpath '@loader_path/../libs/' "
                    + env_dict.get("PADDLE_BINARY_DIR")
                    + '/python/paddle/fluid/'
                    + env_dict.get("FLUID_CORE_NAME")
                    + '.so'
                )
            else:
                commands = [
                    "patchelf --set-rpath '$ORIGIN/../libs/' "
                    + env_dict.get("PADDLE_BINARY_DIR")
                    + '/python/paddle/fluid/'
                    + env_dict.get("FLUID_CORE_NAME")
                    + '.so'
                ]
            # The sw_64 not suppot patchelf, so we just disable that.
            if platform.machine() != 'sw_64' and platform.machine() != 'mips64':
                for command in commands:
                    if os.system(command) != 0:
                        raise Exception(
                            'patch '
                            + env_dict.get("FLUID_CORE_NAME")
                            + '.%s failed' % ext_suffix,
                            'command: %s' % command,
                        )
    # A list of extensions that specify c++ -written modules that compile source code into dynamically linked libraries
    ext_modules = [Extension('_foo', [paddle_binary_dir + '/python/stub.cc'])]
    if os.name == 'nt':
        # fix the path separator under windows
        fix_package_dir = {}
        for k, v in package_dir.items():
            fix_package_dir[k] = v.replace('/', '\\')
        package_dir = fix_package_dir
        ext_modules = []
    elif sys.platform == 'darwin':
        ext_modules = []
    return package_data, package_dir, ext_modules


def get_headers():
    headers = (
1154
        # paddle level api headers (high level api, for both training and inference)
R
risemeup1 已提交
1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165
        list(find_files('*.h', paddle_source_dir + '/paddle'))
        + list(find_files('*.h', paddle_source_dir + '/paddle/phi/api'))
        + list(  # phi unify api header
            find_files('*.h', paddle_source_dir + '/paddle/phi/api/ext')
        )
        + list(  # custom op api
            find_files('*.h', paddle_source_dir + '/paddle/phi/api/include')
        )
        + list(  # phi api
            find_files('*.h', paddle_source_dir + '/paddle/phi/common')
        )
1166
        # phi level api headers (low level api, for training only)
R
risemeup1 已提交
1167
        + list(  # phi extension header
1168 1169 1170
            find_files('*.h', paddle_source_dir + '/paddle/phi')
        )
        + list(  # phi include header
R
risemeup1 已提交
1171 1172 1173 1174
            find_files(
                '*.h', paddle_source_dir + '/paddle/phi/include', recursive=True
            )
        )
1175
        + list(  # phi backends headers
R
risemeup1 已提交
1176 1177 1178 1179 1180 1181
            find_files(
                '*.h',
                paddle_source_dir + '/paddle/phi/backends',
                recursive=True,
            )
        )
1182
        + list(  # phi core headers
R
risemeup1 已提交
1183 1184 1185 1186
            find_files(
                '*.h', paddle_source_dir + '/paddle/phi/core', recursive=True
            )
        )
1187
        + list(  # phi infermeta headers
R
risemeup1 已提交
1188 1189 1190 1191 1192 1193
            find_files(
                '*.h',
                paddle_source_dir + '/paddle/phi/infermeta',
                recursive=True,
            )
        )
1194
        + list(  # phi kernel headers
R
risemeup1 已提交
1195
            find_files(
1196 1197 1198
                '*.h',
                paddle_source_dir + '/paddle/phi/kernels',
                recursive=True,
R
risemeup1 已提交
1199 1200
            )
        )
1201 1202
        # phi capi headers
        + list(
R
risemeup1 已提交
1203 1204 1205 1206
            find_files(
                '*.h', paddle_source_dir + '/paddle/phi/capi', recursive=True
            )
        )
1207
        + list(  # utils api headers
R
risemeup1 已提交
1208
            find_files(
1209
                '*.h', paddle_source_dir + '/paddle/utils', recursive=True
R
risemeup1 已提交
1210 1211 1212 1213
            )
        )
        + list(  # phi profiler headers
            find_files(
1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
                '*.h',
                paddle_source_dir + '/paddle/phi/api/profiler',
                recursive=True,
            )
        )
        + list(  # phi init headers
            find_files(
                'init_phi.h',
                paddle_source_dir + '/paddle/fluid/platform',
                recursive=True,
R
risemeup1 已提交
1224 1225
            )
        )
1226
    )
R
risemeup1 已提交
1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252

    jit_layer_headers = [
        'layer.h',
        'serializer.h',
        'serializer_utils.h',
        'all.h',
        'function.h',
    ]

    for f in jit_layer_headers:
        headers += list(
            find_files(
                f, paddle_source_dir + '/paddle/fluid/jit', recursive=True
            )
        )

    if env_dict.get("WITH_MKLDNN") == 'ON':
        headers += list(
            find_files('*', env_dict.get("MKLDNN_INSTALL_DIR") + '/include')
        )  # mkldnn

    if env_dict.get("WITH_GPU") == 'ON' or env_dict.get("WITH_ROCM") == 'ON':
        # externalErrorMsg.pb for External Error message
        headers += list(
            find_files('*.pb', env_dict.get("externalError_INCLUDE_DIR"))
        )
1253

1254
    if env_dict.get("WITH_XPU") == 'ON':
1255 1256 1257 1258 1259 1260 1261 1262
        headers += list(
            find_files(
                '*.h',
                paddle_binary_dir + '/third_party/xpu/src/extern_xpu/xpu',
                recursive=True,
            )
        )  # xdnn api headers

1263 1264
    # pybind headers
    headers += list(find_files('*.h', env_dict.get("PYBIND_INCLUDE_DIR"), True))
R
risemeup1 已提交
1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331
    return headers


def get_setup_parameters():
    # get setup_requires
    setup_requires = get_setup_requires()
    packages = [
        'paddle',
        'paddle.libs',
        'paddle.utils',
        'paddle.utils.gast',
        'paddle.utils.cpp_extension',
        'paddle.dataset',
        'paddle.reader',
        'paddle.distributed',
        'paddle.distributed.communication',
        'paddle.distributed.communication.stream',
        'paddle.distributed.metric',
        'paddle.distributed.ps',
        'paddle.distributed.ps.utils',
        'paddle.incubate',
        'paddle.incubate.autograd',
        'paddle.incubate.optimizer',
        'paddle.incubate.checkpoint',
        'paddle.incubate.operators',
        'paddle.incubate.tensor',
        'paddle.incubate.multiprocessing',
        'paddle.incubate.nn',
        'paddle.incubate.asp',
        'paddle.incubate.passes',
        'paddle.distribution',
        'paddle.distributed.utils',
        'paddle.distributed.sharding',
        'paddle.distributed.fleet',
        'paddle.distributed.launch',
        'paddle.distributed.launch.context',
        'paddle.distributed.launch.controllers',
        'paddle.distributed.launch.job',
        'paddle.distributed.launch.plugins',
        'paddle.distributed.launch.utils',
        'paddle.distributed.fleet.base',
        'paddle.distributed.fleet.recompute',
        'paddle.distributed.fleet.elastic',
        'paddle.distributed.fleet.meta_optimizers',
        'paddle.distributed.fleet.meta_optimizers.sharding',
        'paddle.distributed.fleet.meta_optimizers.ascend',
        'paddle.distributed.fleet.meta_optimizers.dygraph_optimizer',
        'paddle.distributed.fleet.runtime',
        'paddle.distributed.rpc',
        'paddle.distributed.fleet.dataset',
        'paddle.distributed.fleet.data_generator',
        'paddle.distributed.fleet.metrics',
        'paddle.distributed.fleet.proto',
        'paddle.distributed.fleet.utils',
        'paddle.distributed.fleet.layers',
        'paddle.distributed.fleet.layers.mpu',
        'paddle.distributed.fleet.meta_parallel',
        'paddle.distributed.fleet.meta_parallel.pp_utils',
        'paddle.distributed.fleet.meta_parallel.sharding',
        'paddle.distributed.fleet.meta_parallel.parallel_layers',
        'paddle.distributed.auto_parallel',
        'paddle.distributed.auto_parallel.operators',
        'paddle.distributed.auto_parallel.tuner',
        'paddle.distributed.auto_parallel.cost',
        'paddle.distributed.passes',
        'paddle.distributed.models',
        'paddle.distributed.models.moe',
1332 1333
        'paddle.distributed.transpiler',
        'paddle.distributed.transpiler.details',
R
risemeup1 已提交
1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349
        'paddle.framework',
        'paddle.jit',
        'paddle.jit.dy2static',
        'paddle.inference',
        'paddle.inference.contrib',
        'paddle.inference.contrib.utils',
        'paddle.fluid',
        'paddle.fluid.dygraph',
        'paddle.fluid.proto',
        'paddle.fluid.proto.profiler',
        'paddle.fluid.layers',
        'paddle.fluid.dataloader',
        'paddle.fluid.contrib',
        'paddle.fluid.contrib.extend_optimizer',
        'paddle.fluid.contrib.layers',
        'paddle.fluid.incubate',
meteor135's avatar
meteor135 已提交
1350
        'paddle.incubate.distributed.fleet',
R
risemeup1 已提交
1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378
        'paddle.fluid.incubate.checkpoint',
        'paddle.amp',
        'paddle.cost_model',
        'paddle.hapi',
        'paddle.vision',
        'paddle.vision.models',
        'paddle.vision.transforms',
        'paddle.vision.datasets',
        'paddle.audio',
        'paddle.audio.functional',
        'paddle.audio.features',
        'paddle.audio.datasets',
        'paddle.audio.backends',
        'paddle.text',
        'paddle.text.datasets',
        'paddle.incubate',
        'paddle.incubate.nn',
        'paddle.incubate.nn.functional',
        'paddle.incubate.nn.layer',
        'paddle.incubate.optimizer.functional',
        'paddle.incubate.autograd',
        'paddle.incubate.distributed',
        'paddle.incubate.distributed.utils',
        'paddle.incubate.distributed.utils.io',
        'paddle.incubate.distributed.fleet',
        'paddle.incubate.distributed.models',
        'paddle.incubate.distributed.models.moe',
        'paddle.incubate.distributed.models.moe.gate',
1379 1380 1381 1382
        'paddle.incubate.distributed.fleet.parameter_server',
        'paddle.incubate.distributed.fleet.parameter_server.distribute_transpiler',
        'paddle.incubate.distributed.fleet.parameter_server.ir',
        'paddle.incubate.distributed.fleet.parameter_server.pslib',
1383 1384
        'paddle.quantization',
        'paddle.quantization.quanters',
1385
        'paddle.quantization.observers',
R
risemeup1 已提交
1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396
        'paddle.sparse',
        'paddle.sparse.nn',
        'paddle.sparse.nn.layer',
        'paddle.sparse.nn.functional',
        'paddle.incubate.xpu',
        'paddle.io',
        'paddle.optimizer',
        'paddle.nn',
        'paddle.nn.functional',
        'paddle.nn.layer',
        'paddle.nn.quant',
1397
        'paddle.nn.quant.qat',
R
risemeup1 已提交
1398 1399 1400 1401 1402 1403
        'paddle.nn.initializer',
        'paddle.nn.utils',
        'paddle.metric',
        'paddle.static',
        'paddle.static.nn',
        'paddle.static.amp',
1404
        'paddle.static.amp.bf16',
1405 1406 1407
        'paddle.static.quantization',
        'paddle.quantization',
        'paddle.quantization.imperative',
R
risemeup1 已提交
1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438
        'paddle.tensor',
        'paddle.onnx',
        'paddle.autograd',
        'paddle.device',
        'paddle.device.cuda',
        'paddle.device.xpu',
        'paddle.version',
        'paddle.profiler',
        'paddle.geometric',
        'paddle.geometric.message_passing',
        'paddle.geometric.sampling',
    ]

    paddle_bins = ''
    if not env_dict.get("WIN32"):
        paddle_bins = [
            env_dict.get("PADDLE_BINARY_DIR") + '/paddle/scripts/paddle'
        ]
    package_data, package_dir, ext_modules = get_package_data_and_package_dir()
    headers = get_headers()
    return (
        setup_requires,
        packages,
        paddle_bins,
        package_data,
        package_dir,
        ext_modules,
        headers,
    )


1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459
def check_build_dependency():

    missing_modules = '''Missing build dependency: {dependency}
Please run 'pip install -r python/requirements.txt' to make sure you have all the dependencies installed.
'''.strip()

    with open(TOP_DIR + '/python/requirements.txt') as f:
        build_dependencies = (
            f.read().splitlines()
        )  # Specify the dependencies to install

    python_dependcies_module = []
    installed_packages = []

    for dependency in build_dependencies:
        python_dependcies_module.append(
            re.sub("_|-", '', re.sub(r"==.*|>=.*|<=.*", '', dependency))
        )
    reqs = subprocess.check_output([sys.executable, '-m', 'pip', 'freeze'])

    for r in reqs.split():
R
risemeup1 已提交
1460 1461 1462
        installed_packages.append(
            re.sub("_|-", '', r.decode().split('==')[0]).lower()
        )
1463 1464

    for dependency in python_dependcies_module:
R
risemeup1 已提交
1465
        if dependency.lower() not in installed_packages:
1466 1467 1468
            raise RuntimeError(missing_modules.format(dependency=dependency))


R
risemeup1 已提交
1469 1470 1471 1472
def main():
    # Parse the command line and check arguments before we proceed with building steps and setup
    parse_input_command(filter_args_list)

1473 1474 1475
    # check build dependency
    check_build_dependency()

R
risemeup1 已提交
1476 1477 1478
    # Execute the build process,cmake and make
    if cmake_and_build:
        build_steps()
R
risemeup1 已提交
1479 1480 1481 1482 1483

    if os.getenv("WITH_PYTHON") == "OFF":
        print("only compile, not package")
        return

R
risemeup1 已提交
1484 1485 1486 1487 1488
    build_dir = os.getenv("BUILD_DIR")
    if build_dir is not None:
        env_dict_path = TOP_DIR + '/' + build_dir + '/python'
    else:
        env_dict_path = TOP_DIR + "/build/python/"
1489
    sys.path.insert(1, env_dict_path)
1490
    from env_dict import env_dict
R
risemeup1 已提交
1491 1492 1493

    global env_dict
    global paddle_binary_dir, paddle_source_dir
R
risemeup1 已提交
1494

R
risemeup1 已提交
1495 1496 1497 1498 1499 1500
    paddle_binary_dir = env_dict.get("PADDLE_BINARY_DIR")
    paddle_source_dir = env_dict.get("PADDLE_SOURCE_DIR")

    # preparing parameters for setup()
    paddle_version = env_dict.get("PADDLE_VERSION")
    package_name = env_dict.get("PACKAGE_NAME")
1501

R
risemeup1 已提交
1502 1503 1504 1505 1506 1507
    write_version_py(
        filename='{}/python/paddle/version/__init__.py'.format(
            paddle_binary_dir
        )
    )
    write_cuda_env_config_py(
1508
        filename=f'{paddle_binary_dir}/python/paddle/cuda_env.py'
R
risemeup1 已提交
1509 1510
    )
    write_parameter_server_version_py(
1511
        filename='{}/python/paddle/incubate/distributed/fleet/parameter_server/version.py'.format(
R
risemeup1 已提交
1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526
            paddle_binary_dir
        )
    )
    (
        setup_requires,
        packages,
        scripts,
        package_data,
        package_dir,
        ext_modules,
        headers,
    ) = get_setup_parameters()

    # Log for PYPI, get long_description of setup()
    with open(
1527
        paddle_source_dir + '/python/paddle/README.md', "r", encoding='UTF-8'
R
risemeup1 已提交
1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565
    ) as f:
        long_description = f.read()

    # strip *.so to reduce package size
    if env_dict.get("WITH_STRIP") == 'ON':
        command = (
            'find '
            + paddle_binary_dir
            + '/python/paddle -name "*.so" | xargs -i strip {}'
        )
        if os.system(command) != 0:
            raise Exception("strip *.so failed, command: %s" % command)

    setup(
        name=package_name,
        version=paddle_version,
        description='Parallel Distributed Deep Learning',
        long_description=long_description,
        long_description_content_type="text/markdown",
        author_email="Paddle-better@baidu.com",
        maintainer="PaddlePaddle",
        maintainer_email="Paddle-better@baidu.com",
        url='https://www.paddlepaddle.org.cn/',
        download_url='https://github.com/paddlepaddle/paddle',
        license='Apache Software License',
        packages=packages,
        install_requires=setup_requires,
        ext_modules=ext_modules,
        package_data=package_data,
        package_dir=package_dir,
        scripts=scripts,
        distclass=BinaryDistribution,
        headers=headers,
        cmdclass={
            'install_headers': InstallHeaders,
            'install': InstallCommand,
            'egg_info': EggInfo,
            'install_lib': InstallLib,
1566
            'develop': DevelopCommand,
R
risemeup1 已提交
1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582
        },
        entry_points={
            'console_scripts': [
                'fleetrun = paddle.distributed.launch.main:launch'
            ]
        },
        classifiers=[
            'Development Status :: 5 - Production/Stable',
            'Operating System :: OS Independent',
            'Intended Audience :: Developers',
            'Intended Audience :: Education',
            'Intended Audience :: Science/Research',
            'License :: OSI Approved :: Apache Software License',
            'Programming Language :: C++',
            'Programming Language :: Python :: 3.7',
            'Programming Language :: Python :: 3.8',
1583 1584
            'Programming Language :: Python :: 3.9',
            'Programming Language :: Python :: 3.10',
R
risemeup1 已提交
1585 1586 1587 1588 1589 1590
        ],
    )


if __name__ == '__main__':
    main()