extension_utils.py 41.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# Copyright (c) 2021 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 os
import re
import sys
18
import json
19
import glob
20
import atexit
21
import hashlib
22
import logging
23 24 25 26
import collections
import textwrap
import warnings
import subprocess
27
import threading
28

29
from importlib import machinery
30 31 32
from contextlib import contextmanager
from setuptools.command import bdist_egg

33 34 35 36 37
try:
    from subprocess import DEVNULL  # py3
except ImportError:
    DEVNULL = open(os.devnull, 'wb')

38
from ...fluid import core
39
from ...fluid.framework import OpProtoHolder
40 41
from ...sysconfig import get_include, get_lib

42
logger = logging.getLogger("utils.cpp_extension")
43 44 45 46 47
logger.setLevel(logging.INFO)
formatter = logging.Formatter(fmt='%(asctime)s - %(levelname)s - %(message)s')
ch = logging.StreamHandler()
ch.setFormatter(formatter)
logger.addHandler(ch)
48 49 50

OS_NAME = sys.platform
IS_WINDOWS = OS_NAME.startswith('win')
51 52 53

MSVC_COMPILE_FLAGS = [
    '/MT', '/wd4819', '/wd4251', '/wd4244', '/wd4267', '/wd4275', '/wd4018',
54 55
    '/wd4190', '/EHsc', '/w', '/DGOOGLE_GLOG_DLL_DECL',
    '/DBOOST_HAS_STATIC_ASSERT', '/DNDEBUG', '/DPADDLE_USE_DSO'
56
]
57 58 59 60 61 62 63
CLANG_COMPILE_FLAGS = [
    '-fno-common', '-dynamic', '-DNDEBUG', '-g', '-fwrapv', '-O3', '-arch',
    'x86_64'
]
CLANG_LINK_FLAGS = [
    '-dynamiclib', '-undefined', 'dynamic_lookup', '-arch', 'x86_64'
]
64

65
MSVC_LINK_FLAGS = ['/MACHINE:X64']
66

67 68 69 70 71 72
if core.is_compiled_with_rocm():
    COMMON_HIPCC_FLAGS = [
        '-DPADDLE_WITH_HIP', '-DEIGEN_USE_GPU', '-DEIGEN_USE_HIP'
    ]
else:
    COMMON_NVCC_FLAGS = ['-DPADDLE_WITH_CUDA', '-DEIGEN_USE_GPU']
73

74
GCC_MINI_VERSION = (5, 4, 0)
75
MSVC_MINI_VERSION = (19, 0, 24215)
76 77 78
# Give warning if using wrong compiler
WRONG_COMPILER_WARNING = '''
                        *************************************
79
                        *  Compiler Compatibility WARNING   *
80 81 82 83 84 85 86 87 88
                        *************************************

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

Found that your compiler ({user_compiler}) is not compatible with the compiler 
built Paddle for this platform, which is {paddle_compiler} on {platform}. Please
use {paddle_compiler} to compile your custom op. Or you may compile Paddle from
source using {user_compiler}, and then also use it compile your custom op.

89
See https://www.paddlepaddle.org.cn/documentation/docs/zh/install/compile/fromsource.html
90 91 92 93 94 95 96 97 98 99 100 101
for help with compiling Paddle from source.

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
'''
# Give warning if used compiler version is incompatible
ABI_INCOMPATIBILITY_WARNING = '''
                            **********************************
                            *    ABI Compatibility WARNING   *
                            **********************************

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

102
Found that your compiler ({user_compiler} == {version}) may be ABI-incompatible with pre-installed Paddle!
103 104 105 106 107 108 109
Please use compiler that is ABI-compatible with GCC >= 5.4 (Recommended 8.2).

See https://gcc.gnu.org/onlinedocs/libstdc++/manual/abi.html for ABI Compatibility
information

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
'''
110

111 112 113 114 115
DEFAULT_OP_ATTR_NAMES = [
    core.op_proto_and_checker_maker.kOpRoleAttrName(),
    core.op_proto_and_checker_maker.kOpRoleVarAttrName(),
    core.op_proto_and_checker_maker.kOpNameScopeAttrName(),
    core.op_proto_and_checker_maker.kOpCreationCallstackAttrName(),
116 117
    core.op_proto_and_checker_maker.kOpDeviceAttrName(),
    core.op_proto_and_checker_maker.kOpWithQuantAttrName()
118 119
]

120

121 122 123 124 125 126 127 128 129 130 131 132
@contextmanager
def bootstrap_context():
    """
    Context to manage how to write `__bootstrap__` code in .egg
    """
    origin_write_stub = bdist_egg.write_stub
    bdist_egg.write_stub = custom_write_stub
    yield

    bdist_egg.write_stub = origin_write_stub


133
def load_op_meta_info_and_register_op(lib_filename):
134
    core.load_op_meta_info_and_register_op(lib_filename)
135 136 137
    return OpProtoHolder.instance().update_op_proto()


138 139 140 141 142 143 144 145
def custom_write_stub(resource, pyfile):
    """
    Customized write_stub function to allow us to inject generated python
    api codes into egg python file.
    """
    _stub_template = textwrap.dedent("""
        import os
        import sys
146
        import types
147 148
        import paddle
        
149 150 151
        cur_dir = os.path.dirname(os.path.abspath(__file__))
        so_path = os.path.join(cur_dir, "{resource}")
        
152
        def inject_ext_module(module_name, api_names):
153 154 155
            if module_name in sys.modules:
                return sys.modules[module_name]

156
            new_module = types.ModuleType(module_name)
157 158
            for api_name in api_names:
                setattr(new_module, api_name, eval(api_name))
159 160 161 162 163 164 165

            return new_module

        def __bootstrap__():
            assert os.path.exists(so_path)

            # load custom op shared library with abs path
166 167
            new_custom_ops = paddle.utils.cpp_extension.load_op_meta_info_and_register_op(so_path)
            m = inject_ext_module(__name__, new_custom_ops)
168 169 170 171
        
        __bootstrap__()

        {custom_api}
172

173 174 175 176
        """).lstrip()

    # Parse registerring op information
    _, op_info = CustomOpInfo.instance().last()
177
    so_path = op_info.so_path
178

179 180 181 182 183
    new_custom_ops = load_op_meta_info_and_register_op(so_path)
    assert len(
        new_custom_ops
    ) > 0, "Required at least one custom operators, but received len(custom_op) =  %d" % len(
        new_custom_ops)
184 185 186 187 188 189

    # NOTE: To avoid importing .so file instead of python file because they have same name,
    # we rename .so shared library to another name, see EasyInstallCommand.
    filename, ext = os.path.splitext(resource)
    resource = filename + "_pd_" + ext

190 191 192 193
    api_content = []
    for op_name in new_custom_ops:
        api_content.append(_custom_api_content(op_name))

194 195 196
    with open(pyfile, 'w') as f:
        f.write(
            _stub_template.format(
197
                resource=resource, custom_api='\n\n'.join(api_content)))
198 199


200
OpInfo = collections.namedtuple('OpInfo', ['so_name', 'so_path'])
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220


class CustomOpInfo:
    """
    A global Singleton map to record all compiled custom ops information.
    """

    @classmethod
    def instance(cls):
        if not hasattr(cls, '_instance'):
            cls._instance = cls()
        return cls._instance

    def __init__(self):
        assert not hasattr(
            self.__class__,
            '_instance'), 'Please use `instance()` to get CustomOpInfo object!'
        # NOTE(Aurelius84): Use OrderedDict to save more order information
        self.op_info_map = collections.OrderedDict()

221 222
    def add(self, op_name, so_name, so_path=None):
        self.op_info_map[op_name] = OpInfo(so_name, so_path)
223 224 225 226 227 228 229 230 231

    def last(self):
        """
        Return the lastest insert custom op info.
        """
        assert len(self.op_info_map) > 0
        return next(reversed(self.op_info_map.items()))


232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
VersionFields = collections.namedtuple('VersionFields', [
    'sources',
    'extra_compile_args',
    'extra_link_args',
    'library_dirs',
    'runtime_library_dirs',
    'include_dirs',
    'define_macros',
    'undef_macros',
])


class VersionManager:
    def __init__(self, version_field):
        self.version_field = version_field
        self.version = self.hasher(version_field)

    def hasher(self, version_field):
        from paddle.fluid.layers.utils import flatten

        md5 = hashlib.md5()
        for field in version_field._fields:
            elem = getattr(version_field, field)
            if not elem: continue
            if isinstance(elem, (list, tuple, dict)):
                flat_elem = flatten(elem)
                md5 = combine_hash(md5, tuple(flat_elem))
            else:
                raise RuntimeError(
                    "Support types with list, tuple and dict, but received {} with {}.".
                    format(type(elem), elem))

        return md5.hexdigest()

    @property
    def details(self):
        return self.version_field._asdict()


def combine_hash(md5, value):
    """
    Return new hash value.
274
    DO NOT use `hash()` because it doesn't generate stable value between different process.
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
    See https://stackoverflow.com/questions/27522626/hash-function-in-python-3-3-returns-different-results-between-sessions
    """
    md5.update(repr(value).encode())
    return md5


def clean_object_if_change_cflags(so_path, extension):
    """
    If already compiling source before, we should check whether cflags 
    have changed and delete the built object to re-compile the source
    even though source file content keeps unchanaged.
    """

    def serialize(path, version_info):
        assert isinstance(version_info, dict)
        with open(path, 'w') as f:
            f.write(json.dumps(version_info, indent=4, sort_keys=True))

    def deserialize(path):
        assert os.path.exists(path)
        with open(path, 'r') as f:
            content = f.read()
            return json.loads(content)

    # version file
    VERSION_FILE = "version.txt"
    base_dir = os.path.dirname(so_path)
    so_name = os.path.basename(so_path)
    version_file = os.path.join(base_dir, VERSION_FILE)

    # version info
    args = [getattr(extension, field, None) for field in VersionFields._fields]
    version_field = VersionFields._make(args)
    versioner = VersionManager(version_field)

    if os.path.exists(so_path) and os.path.exists(version_file):
        old_version_info = deserialize(version_file)
        so_version = old_version_info.get(so_name, None)
313
        # delete shared library file if version is changed to re-compile it.
314 315 316 317 318
        if so_version is not None and so_version != versioner.version:
            log_v(
                "Re-Compiling {}, because specified cflags have been changed. New signature {} has been saved into {}.".
                format(so_name, versioner.version, version_file))
            os.remove(so_path)
319
            # update new version information
320 321 322 323 324 325 326 327 328 329 330 331
            new_version_info = versioner.details
            new_version_info[so_name] = versioner.version
            serialize(version_file, new_version_info)
    else:
        # If compile at first time, save compiling detail information for debug.
        if not os.path.exists(base_dir):
            os.makedirs(base_dir)
        details = versioner.details
        details[so_name] = versioner.version
        serialize(version_file, details)


332
def prepare_unix_cudaflags(cflags):
333 334 335
    """
    Prepare all necessary compiled flags for nvcc compiling CUDA files.
    """
336 337 338 339 340 341 342 343
    if core.is_compiled_with_rocm():
        cflags = COMMON_HIPCC_FLAGS + ['-Xcompiler', '-fPIC'
                                       ] + cflags + get_rocm_arch_flags(cflags)
    else:
        cflags = COMMON_NVCC_FLAGS + [
            '-ccbin', 'cc', '-Xcompiler', '-fPIC', '--expt-relaxed-constexpr',
            '-DNVCC'
        ] + cflags + get_cuda_arch_flags(cflags)
344 345 346 347

    return cflags


348
def prepare_win_cudaflags(cflags):
349 350 351
    """
    Prepare all necessary compiled flags for nvcc compiling CUDA files.
    """
352
    cflags = COMMON_NVCC_FLAGS + ['-w'] + cflags + get_cuda_arch_flags(cflags)
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

    return cflags


def add_std_without_repeat(cflags, compiler_type, use_std14=False):
    """
    Append -std=c++11/14 in cflags if without specific it before.
    """
    cpp_flag_prefix = '/std:' if compiler_type == 'msvc' else '-std='
    if not any(cpp_flag_prefix in flag for flag in cflags):
        suffix = 'c++14' if use_std14 else 'c++11'
        cpp_flag = cpp_flag_prefix + suffix
        cflags.append(cpp_flag)


def get_cuda_arch_flags(cflags):
    """
    For an arch, say "6.1", the added compile flag will be
    ``-gencode=arch=compute_61,code=sm_61``.
    For an added "+PTX", an additional
    ``-gencode=arch=compute_xx,code=compute_xx`` is added.
    """
    # TODO(Aurelius84):
    return []


379 380 381 382 383 384 385 386
def get_rocm_arch_flags(cflags):
    """
    For ROCm platform, amdgpu target should be added for HIPCC.
    """
    cflags = cflags + ['-fno-gpu-rdc', '-amdgpu-target=gfx906']
    return cflags


387 388 389 390 391 392 393 394 395 396 397 398 399
def _get_fluid_path():
    """
    Return installed fluid dir path.
    """
    import paddle
    return os.path.join(os.path.dirname(paddle.__file__), 'fluid')


def _get_core_name():
    """
    Return pybind DSO module name.
    """
    import paddle
400 401 402
    ext_name = '.pyd' if IS_WINDOWS else '.so'
    if not paddle.fluid.core.load_noavx:
        return 'core_avx' + ext_name
403
    else:
404
        return 'core_noavx' + ext_name
405 406 407 408 409 410 411 412 413 414 415


def _get_lib_core_path():
    """
    Return real path of libcore_(no)avx.dylib on MacOS.
    """
    raw_core_name = _get_core_name()
    lib_core_name = "lib{}.dylib".format(raw_core_name[:-3])
    return os.path.join(_get_fluid_path(), lib_core_name)


416 417 418 419 420 421 422 423 424
def _get_dll_core_path():
    """
    Return real path of libcore_(no)avx.dylib on Windows.
    """
    raw_core_name = _get_core_name()
    dll_core_name = "paddle_pybind.dll"
    return os.path.join(_get_fluid_path(), dll_core_name)


425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
def _reset_so_rpath(so_path):
    """
    NOTE(Aurelius84): Runtime path of core_(no)avx.so is modified into `@loader_path/../libs`
    in setup.py.in. While loading custom op, `@loader_path` is the dirname of custom op
    instead of `paddle/fluid`. So we modify `@loader_path` from custom dylib into `@rpath`
    to ensure dynamic loader find it correctly.

    Moreover, we will add `-rpath site-packages/paddle/fluid` while linking the dylib so
    that we don't need to set `LD_LIBRARY_PATH` any more.
    """
    assert os.path.exists(so_path)
    if OS_NAME.startswith("darwin"):
        origin_runtime_path = "@loader_path/../libs/"
        rpath = "@rpath/{}".format(_get_core_name())
        cmd = 'install_name_tool -change {} {} {}'.format(origin_runtime_path,
                                                          rpath, so_path)

        run_cmd(cmd)


445 446 447 448 449 450 451 452
def _get_include_dirs_when_compiling(compile_dir):
    """
    Get all include directories when compiling the PaddlePaddle
    source code.
    """
    include_dirs_file = 'includes.txt'
    path = os.path.abspath(compile_dir)
    include_dirs_file = os.path.join(path, include_dirs_file)
453 454
    assert os.path.isfile(include_dirs_file), "File {} does not exist".format(
        include_dirs_file)
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
    with open(include_dirs_file, 'r') as f:
        include_dirs = [line.strip() for line in f.readlines() if line.strip()]

    extra_dirs = ['paddle/fluid/platform']
    all_include_dirs = list(include_dirs)
    for extra_dir in extra_dirs:
        for include_dir in include_dirs:
            d = os.path.join(include_dir, extra_dir)
            if os.path.isdir(d):
                all_include_dirs.append(d)
    all_include_dirs.append(path)
    all_include_dirs.sort()
    return all_include_dirs


470
def normalize_extension_kwargs(kwargs, use_cuda=False):
471
    """
472 473 474
    Normalize include_dirs, library_dir and other attributes in kwargs.
    """
    assert isinstance(kwargs, dict)
475
    compile_include_dirs = []
476 477 478 479 480
    # NOTE: the "_compile_dir" argument is not public to users. It is only
    # reserved for internal usage. We do not guarantee that this argument
    # is always valid in the future release versions.
    compile_dir = kwargs.get("_compile_dir", None)
    if compile_dir:
481
        compile_include_dirs = _get_include_dirs_when_compiling(compile_dir)
482

483
    # append necessary include dir path of paddle
484 485
    include_dirs = list(kwargs.get('include_dirs', []))
    include_dirs.extend(compile_include_dirs)
486
    include_dirs.extend(find_paddle_includes(use_cuda))
487

488 489 490 491 492 493 494
    kwargs['include_dirs'] = include_dirs

    # append necessary lib path of paddle
    library_dirs = kwargs.get('library_dirs', [])
    library_dirs.extend(find_paddle_libraries(use_cuda))
    kwargs['library_dirs'] = library_dirs

495 496 497 498 499 500 501
    # append compile flags and check settings of compiler
    extra_compile_args = kwargs.get('extra_compile_args', [])
    if isinstance(extra_compile_args, dict):
        for compiler in ['cxx', 'nvcc']:
            if compiler not in extra_compile_args:
                extra_compile_args[compiler] = []

502 503 504 505 506 507
    if IS_WINDOWS:
        # TODO(zhouwei): may append compile flags in future
        pass
        # append link flags
        extra_link_args = kwargs.get('extra_link_args', [])
        extra_link_args.extend(MSVC_LINK_FLAGS)
508 509
        lib_core_name = create_sym_link_if_not_exist()
        extra_link_args.append('{}'.format(lib_core_name))
510 511
        if use_cuda:
            extra_link_args.extend(['cudadevrt.lib', 'cudart_static.lib'])
512
        kwargs['extra_link_args'] = extra_link_args
513

514
    else:
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
        ########################### Linux Platform ###########################
        extra_link_args = kwargs.get('extra_link_args', [])
        # On Linux, GCC support '-l:xxx.so' to specify the library name
        # without `lib` prefix.
        if OS_NAME.startswith('linux'):
            extra_link_args.append('-l:{}'.format(_get_core_name()))
        ########################### MacOS Platform ###########################
        else:
            # See _reset_so_rpath for details.
            extra_link_args.append('-Wl,-rpath,{}'.format(_get_fluid_path()))
            # On MacOS, ld don't support `-l:xx`, so we create a
            # libcore_avx.dylib symbol link.
            lib_core_name = create_sym_link_if_not_exist()
            extra_link_args.append('-l{}'.format(lib_core_name))
        ###########################   -- END --    ###########################

531
        add_compile_flag(extra_compile_args, ['-w'])  # disable warning
532

533
        if use_cuda:
534 535 536 537
            if core.is_compiled_with_rocm():
                extra_link_args.append('-lamdhip64')
            else:
                extra_link_args.append('-lcudart')
538

539
        kwargs['extra_link_args'] = extra_link_args
540

541 542 543 544
        # add runtime library dirs
        runtime_library_dirs = kwargs.get('runtime_library_dirs', [])
        runtime_library_dirs.extend(find_paddle_libraries(use_cuda))
        kwargs['runtime_library_dirs'] = runtime_library_dirs
545

546 547 548
    if compile_dir is None:
        # Add this compile option to isolate fluid headers
        add_compile_flag(extra_compile_args, ['-DPADDLE_WITH_CUSTOM_KERNEL'])
549 550
    kwargs['extra_compile_args'] = extra_compile_args

551 552 553 554
    kwargs['language'] = 'c++'
    return kwargs


555 556 557 558
def create_sym_link_if_not_exist():
    """
    Create soft symbol link of `core_avx.so` or `core_noavx.so`
    """
559
    assert OS_NAME.startswith('darwin') or IS_WINDOWS
560 561 562

    raw_core_name = _get_core_name()
    core_path = os.path.join(_get_fluid_path(), raw_core_name)
563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
    if IS_WINDOWS:
        new_dll_core_path = _get_dll_core_path()
        # create symbol link on windows
        if not os.path.exists(new_dll_core_path):
            try:
                os.symlink(core_path, new_dll_core_path)
            except Exception:
                warnings.warn(
                    "Failed to create soft symbol link for {}.\n You can run prompt as administrator and execute the "
                    "following command manually: `mklink {} {}`. Now it will create hard link for {} trickly.".
                    format(raw_core_name, new_dll_core_path, core_path,
                           raw_core_name))
                run_cmd('mklink /H {} {}'.format(new_dll_core_path, core_path))
        # core_avx or core_noavx with lib suffix
        assert os.path.exists(new_dll_core_path)
        return raw_core_name[:-4] + ".lib"
579

580 581 582 583 584 585 586 587 588 589 590
    else:
        new_lib_core_path = _get_lib_core_path()
        # create symbol link on mac
        if not os.path.exists(new_lib_core_path):
            try:
                os.symlink(core_path, new_lib_core_path)
                assert os.path.exists(new_lib_core_path)
            except Exception:
                raise RuntimeError(
                    "Failed to create soft symbol link for {}.\n Please execute the following command manually: `ln -s {} {}`".
                    format(raw_core_name, core_path, new_lib_core_path))
591

592 593
        # core_avx or core_noavx without suffix
        return raw_core_name[:-3]
594 595


596 597 598 599 600 601 602 603 604 605 606 607 608 609
def find_cuda_home():
    """
    Use heuristic method to find cuda path
    """
    # step 1. find in $CUDA_HOME or $CUDA_PATH
    cuda_home = os.environ.get('CUDA_HOME') or os.environ.get('CUDA_PATH')

    # step 2.  find path by `which nvcc`
    if cuda_home is None:
        which_cmd = 'where' if IS_WINDOWS else 'which'
        try:
            with open(os.devnull, 'w') as devnull:
                nvcc_path = subprocess.check_output(
                    [which_cmd, 'nvcc'], stderr=devnull)
T
tianshuo78520a 已提交
610
                nvcc_path = nvcc_path.decode()
611 612
                # Multi CUDA, select the first
                nvcc_path = nvcc_path.split('\r\n')[0]
613

614 615 616 617 618 619
                # for example: /usr/local/cuda/bin/nvcc
                cuda_home = os.path.dirname(os.path.dirname(nvcc_path))
        except:
            if IS_WINDOWS:
                # search from default NVIDIA GPU path
                candidate_paths = glob.glob(
620 621
                    'C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v*.*'
                )
622 623 624 625 626
                if len(candidate_paths) > 0:
                    cuda_home = candidate_paths[0]
            else:
                cuda_home = "/usr/local/cuda"
    # step 3. check whether path is valid
627 628
    if cuda_home and not os.path.exists(
            cuda_home) and core.is_compiled_with_cuda():
629 630 631 632 633
        cuda_home = None

    return cuda_home


634 635 636 637 638 639 640 641 642 643 644 645 646 647
def find_rocm_home():
    """
    Use heuristic method to find rocm path
    """
    # step 1. find in $ROCM_HOME or $ROCM_PATH
    rocm_home = os.environ.get('ROCM_HOME') or os.environ.get('ROCM_PATH')

    # step 2.  find path by `which nvcc`
    if rocm_home is None:
        which_cmd = 'where' if IS_WINDOWS else 'which'
        try:
            with open(os.devnull, 'w') as devnull:
                hipcc_path = subprocess.check_output(
                    [which_cmd, 'hipcc'], stderr=devnull)
T
tianshuo78520a 已提交
648
                hipcc_path = hipcc_path.decode()
649 650 651 652 653 654 655 656 657 658 659 660 661 662
                hipcc_path = hipcc_path.rstrip('\r\n')

                # for example: /opt/rocm/bin/hipcc
                rocm_home = os.path.dirname(os.path.dirname(hipcc_path))
        except:
            rocm_home = "/opt/rocm"
    # step 3. check whether path is valid
    if rocm_home and not os.path.exists(
            rocm_home) and core.is_compiled_with_rocm():
        rocm_home = None

    return rocm_home


663 664 665 666 667 668 669 670 671 672 673 674 675
def find_cuda_includes():
    """
    Use heuristic method to find cuda include path
    """
    cuda_home = find_cuda_home()
    if cuda_home is None:
        raise ValueError(
            "Not found CUDA runtime, please use `export CUDA_HOME=XXX` to specific it."
        )

    return [os.path.join(cuda_home, 'include')]


676 677 678 679 680 681 682 683 684 685 686 687 688
def find_rocm_includes():
    """
    Use heuristic method to find rocm include path
    """
    rocm_home = find_rocm_home()
    if rocm_home is None:
        raise ValueError(
            "Not found ROCM runtime, please use `export ROCM_PATH= XXX` to specific it."
        )

    return [os.path.join(rocm_home, 'include')]


689 690 691 692 693 694 695 696 697
def find_paddle_includes(use_cuda=False):
    """
    Return Paddle necessary include dir path.
    """
    # pythonXX/site-packages/paddle/include
    paddle_include_dir = get_include()
    third_party_dir = os.path.join(paddle_include_dir, 'third_party')
    include_dirs = [paddle_include_dir, third_party_dir]

698
    if use_cuda:
699 700 701 702 703 704
        if core.is_compiled_with_rocm():
            rocm_include_dir = find_rocm_includes()
            include_dirs.extend(rocm_include_dir)
        else:
            cuda_include_dir = find_cuda_includes()
            include_dirs.extend(cuda_include_dir)
705

706 707
    if OS_NAME.startswith('darwin'):
        # NOTE(Aurelius84): Ensure to find std v1 headers correctly.
708 709 710
        std_v1_includes = find_clang_cpp_include()
        if std_v1_includes is not None and os.path.exists(std_v1_includes):
            include_dirs.append(std_v1_includes)
711

712 713 714
    return include_dirs


715 716 717 718
def find_clang_cpp_include(compiler='clang'):
    std_v1_includes = None
    try:
        compiler_version = subprocess.check_output([compiler, "--version"])
T
tianshuo78520a 已提交
719
        compiler_version = compiler_version.decode()
720 721 722 723 724 725 726 727 728 729 730 731 732 733 734
        infos = compiler_version.split("\n")
        for info in infos:
            if "InstalledDir" in info:
                v1_path = info.split(':')[-1].strip()
                if v1_path and os.path.exists(v1_path):
                    std_v1_includes = os.path.join(
                        os.path.dirname(v1_path), 'include/c++/v1')
    except Exception:
        # Just raise warnings because the include dir is not required.
        warnings.warn(
            "Failed to search `include/c++/v1/` include dirs. Don't worry because it's not required."
        )
    return std_v1_includes


735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
def find_cuda_libraries():
    """
    Use heuristic method to find cuda static lib path
    """
    cuda_home = find_cuda_home()
    if cuda_home is None:
        raise ValueError(
            "Not found CUDA runtime, please use `export CUDA_HOME=XXX` to specific it."
        )
    if IS_WINDOWS:
        cuda_lib_dir = [os.path.join(cuda_home, 'lib', 'x64')]
    else:
        cuda_lib_dir = [os.path.join(cuda_home, 'lib64')]

    return cuda_lib_dir


752 753 754 755 756 757 758 759 760 761 762 763 764 765
def find_rocm_libraries():
    """
    Use heuristic method to find rocm dynamic lib path
    """
    rocm_home = find_rocm_home()
    if rocm_home is None:
        raise ValueError(
            "Not found ROCM runtime, please use `export ROCM_PATH=XXX` to specific it."
        )
    rocm_lib_dir = [os.path.join(rocm_home, 'lib')]

    return rocm_lib_dir


766 767 768 769 770 771
def find_paddle_libraries(use_cuda=False):
    """
    Return Paddle necessary library dir path.
    """
    # pythonXX/site-packages/paddle/libs
    paddle_lib_dirs = [get_lib()]
772

773
    if use_cuda:
774 775 776 777 778 779
        if core.is_compiled_with_rocm():
            rocm_lib_dir = find_rocm_libraries()
            paddle_lib_dirs.extend(rocm_lib_dir)
        else:
            cuda_lib_dir = find_cuda_libraries()
            paddle_lib_dirs.extend(cuda_lib_dir)
780

781 782 783
    # add `paddle/fluid` to search `core_avx.so` or `core_noavx.so`
    paddle_lib_dirs.append(_get_fluid_path())

784 785 786
    return paddle_lib_dirs


787 788
def add_compile_flag(extra_compile_args, flags):
    assert isinstance(flags, list)
789 790
    if isinstance(extra_compile_args, dict):
        for args in extra_compile_args.values():
791
            args.extend(flags)
792
    else:
793
        extra_compile_args.extend(flags)
794 795 796 797 798 799 800 801 802 803


def is_cuda_file(path):

    cuda_suffix = set(['.cu'])
    items = os.path.splitext(path)
    assert len(items) > 1
    return items[-1] in cuda_suffix


804
def get_build_directory(verbose=False):
805
    """
806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821
    Return paddle extension root directory to put shared library. It could be specified by
    ``export PADDLE_EXTENSION_DIR=XXX`` . If not set, ``~/.cache/paddle_extension`` will be used
    by default.

    Returns:
        The root directory of compiling customized operators.

    Examples:

    .. code-block:: python

        from paddle.utils.cpp_extension import get_build_directory

        build_dir = get_build_directory()
        print(build_dir)

822 823 824 825
    """
    root_extensions_directory = os.environ.get('PADDLE_EXTENSION_DIR')
    if root_extensions_directory is None:
        dir_name = "paddle_extensions"
826 827 828 829 830
        root_extensions_directory = os.path.join(
            os.path.expanduser('~/.cache'), dir_name)
        if IS_WINDOWS:
            root_extensions_directory = os.path.normpath(
                root_extensions_directory)
831

832 833
        log_v("$PADDLE_EXTENSION_DIR is not set, using path: {} by default.".
              format(root_extensions_directory), verbose)
834 835 836 837 838 839 840 841 842 843 844 845 846 847

    if not os.path.exists(root_extensions_directory):
        os.makedirs(root_extensions_directory)

    return root_extensions_directory


def parse_op_info(op_name):
    """
    Parse input names and outpus detail information from registered custom op
    from OpInfoMap.
    """
    if op_name not in OpProtoHolder.instance().op_proto_map:
        raise ValueError(
848
            "Please load {} shared library file firstly by `paddle.utils.cpp_extension.load_op_meta_info_and_register_op(...)`".
849 850 851 852
            format(op_name))
    op_proto = OpProtoHolder.instance().get_op_proto(op_name)

    in_names = [x.name for x in op_proto.inputs]
853
    out_names = [x.name for x in op_proto.outputs]
854 855 856
    attr_names = [
        x.name for x in op_proto.attrs if x.name not in DEFAULT_OP_ATTR_NAMES
    ]
857

858
    return in_names, out_names, attr_names
859 860


861
def _import_module_from_library(module_name, build_directory, verbose=False):
862
    """
863
    Load shared library and import it as callable python module.
864
    """
865 866
    if IS_WINDOWS:
        dynamic_suffix = '.pyd'
867 868
    elif OS_NAME.startswith('darwin'):
        dynamic_suffix = '.dylib'
869 870 871
    else:
        dynamic_suffix = '.so'
    ext_path = os.path.join(build_directory, module_name + dynamic_suffix)
872 873 874 875 876
    if not os.path.exists(ext_path):
        raise FileNotFoundError("Extension path: {} does not exist.".format(
            ext_path))

    # load custom op_info and kernels from .so shared library
877
    log_v('loading shared library from: {}'.format(ext_path), verbose)
878
    op_names = load_op_meta_info_and_register_op(ext_path)
879 880

    # generate Python api in ext_path
881 882
    return _generate_python_module(module_name, op_names, build_directory,
                                   verbose)
883 884


885 886 887 888
def _generate_python_module(module_name,
                            op_names,
                            build_directory,
                            verbose=False):
889 890 891
    """
    Automatically generate python file to allow import or load into as module
    """
892 893 894 895 896 897 898 899 900 901

    def remove_if_exit(filepath):
        if os.path.exists(filepath):
            os.remove(filepath)

    # NOTE: Use unique id as suffix to avoid write same file at same time in
    # both multi-thread and multi-process.
    thread_id = str(threading.currentThread().ident)
    api_file = os.path.join(build_directory,
                            module_name + '_' + thread_id + '.py')
902
    log_v("generate api file: {}".format(api_file), verbose)
903

904 905 906
    # delete the temp file before exit python process    
    atexit.register(lambda: remove_if_exit(api_file))

907
    # write into .py file with RWLockc
908
    api_content = [_custom_api_content(op_name) for op_name in op_names]
909
    with open(api_file, 'w') as f:
910
        f.write('\n\n'.join(api_content))
911 912

    # load module
913
    custom_module = _load_module_from_file(api_file, module_name, verbose)
914
    return custom_module
915 916 917


def _custom_api_content(op_name):
918 919 920
    params_str, ins_str, attrs_str, outs_str, in_names, attrs_names = _get_api_inputs_str(
        op_name)
    lower_in_names = [p.split("@")[0].lower() for p in in_names]
921
    API_TEMPLATE = textwrap.dedent("""
922 923
        import paddle.fluid.core as core
        from paddle.fluid.core import VarBase, CustomOpKernelContext
J
Jiabin Yang 已提交
924
        from paddle.fluid.framework import _non_static_mode, _dygraph_tracer, _in_legacy_dygraph, in_dygraph_mode
925
        from paddle.fluid.layer_helper import LayerHelper
926
        
927
        def {op_name}({inputs}):
928
            # prepare inputs and outputs
929
            ins = {ins}
930
            attrs = {attrs}
931
            outs = {{}}
932
            out_names = {out_names}
933

934 935 936
            # The output variable's dtype use default value 'float32',
            # and the actual dtype of output variable will be inferred in runtime.
            if in_dygraph_mode():
J
Jiabin Yang 已提交
937 938 939 940 941 942 943 944 945 946 947
                ctx = CustomOpKernelContext()
                for i in {in_names}:
                    ctx.add_inputs(i)
                for j in {attr_names}:
                    ctx.add_attr(j)
                for out_name in out_names:
                    outs[out_name] = core.eager.Tensor()
                    ctx.add_outputs(outs[out_name])
                core.eager._run_custom_op(ctx, "{op_name}", True)
            else:
                if _in_legacy_dygraph():
948 949 950
                    for out_name in out_names:
                        outs[out_name] = VarBase()
                    _dygraph_tracer().trace_op(type="{op_name}", inputs=ins, outputs=outs, attrs=attrs)
J
Jiabin Yang 已提交
951 952 953 954
                else:
                    helper = LayerHelper("{op_name}", **locals())
                    for out_name in out_names:
                        outs[out_name] = helper.create_variable(dtype='float32')
955

J
Jiabin Yang 已提交
956
                    helper.append_op(type="{op_name}", inputs=ins, outputs=outs, attrs=attrs)
957

958 959 960
            res = [outs[out_name] for out_name in out_names]

            return res[0] if len(res)==1 else res
961 962 963 964
            """).lstrip()

    # generate python api file
    api_content = API_TEMPLATE.format(
965 966 967 968
        op_name=op_name,
        inputs=params_str,
        ins=ins_str,
        attrs=attrs_str,
969 970 971
        # "[x, y, z]""
        in_names="[" + ",".join(lower_in_names) + "]",
        attr_names="[" + ",".join(attrs_names) + "]",
972
        out_names=outs_str)
973 974 975 976

    return api_content


977
def _load_module_from_file(api_file_path, module_name, verbose=False):
978 979 980 981 982 983 984 985
    """
    Load module from python file.
    """
    if not os.path.exists(api_file_path):
        raise FileNotFoundError("File : {} does not exist.".format(
            api_file_path))

    # Unique readable module name to place custom api.
986
    log_v('import module from file: {}'.format(api_file_path), verbose)
987 988 989
    ext_name = "_paddle_cpp_extension_" + module_name

    # load module with RWLock
T
tianshuo78520a 已提交
990 991
    loader = machinery.SourceFileLoader(ext_name, api_file_path)
    module = loader.load_module()
992

993
    return module
994 995 996 997 998 999


def _get_api_inputs_str(op_name):
    """
    Returns string of api parameters and inputs dict.
    """
1000
    in_names, out_names, attr_names = parse_op_info(op_name)
1001
    # e.g: x, y, z
1002
    param_names = in_names + attr_names
1003
    # NOTE(chenweihang): we add suffix `@VECTOR` for std::vector<Tensor> input,
1004
    # but the string contains `@` cannot used as argument name, so we split
1005 1006
    # input name by `@`, and only use first substr as argument
    params_str = ','.join([p.split("@")[0].lower() for p in param_names])
1007
    # e.g: {'X': x, 'Y': y, 'Z': z}
1008 1009 1010 1011
    ins_str = "{%s}" % ','.join([
        "'{}' : {}".format(in_name, in_name.split("@")[0].lower())
        for in_name in in_names
    ])
1012 1013
    # e.g: {'num': n}
    attrs_str = "{%s}" % ",".join([
1014
        "'{}' : {}".format(attr_name, attr_name.split("@")[0].lower())
1015 1016
        for attr_name in attr_names
    ])
1017 1018
    # e.g: ['Out', 'Index']
    outs_str = "[%s]" % ','.join(["'{}'".format(name) for name in out_names])
1019
    return params_str, ins_str, attrs_str, outs_str, in_names, attr_names
1020 1021


1022 1023 1024
def _write_setup_file(name,
                      sources,
                      file_path,
1025
                      build_dir,
1026
                      include_dirs,
1027 1028
                      extra_cxx_cflags,
                      extra_cuda_cflags,
1029 1030
                      link_args,
                      verbose=False):
1031 1032 1033 1034 1035 1036 1037
    """
    Automatically generate setup.py and write it into build directory.
    """
    template = textwrap.dedent("""
    import os
    from paddle.utils.cpp_extension import CppExtension, CUDAExtension, BuildExtension, setup
    from paddle.utils.cpp_extension import get_build_directory
1038 1039


1040 1041 1042 1043 1044 1045
    setup(
        name='{name}',
        ext_modules=[
            {prefix}Extension(
                sources={sources},
                include_dirs={include_dirs},
1046
                extra_compile_args={{'cxx':{extra_cxx_cflags}, 'nvcc':{extra_cuda_cflags}}},
1047 1048
                extra_link_args={extra_link_args})],
        cmdclass={{"build_ext" : BuildExtension.with_options(
1049 1050
            output_dir=r'{build_dir}',
            no_python_abi_suffix=True)
1051 1052 1053 1054 1055
        }})""").lstrip()

    with_cuda = False
    if any([is_cuda_file(source) for source in sources]):
        with_cuda = True
1056
    log_v("with_cuda: {}".format(with_cuda), verbose)
1057 1058 1059 1060 1061 1062

    content = template.format(
        name=name,
        prefix='CUDA' if with_cuda else 'Cpp',
        sources=list2str(sources),
        include_dirs=list2str(include_dirs),
1063 1064
        extra_cxx_cflags=list2str(extra_cxx_cflags),
        extra_cuda_cflags=list2str(extra_cuda_cflags),
1065
        extra_link_args=list2str(link_args),
1066
        build_dir=build_dir)
1067 1068

    log_v('write setup.py into {}'.format(file_path), verbose)
1069 1070 1071 1072 1073 1074
    with open(file_path, 'w') as f:
        f.write(content)


def list2str(args):
    """
1075
    Convert list[str] into string. For example: ['x', 'y'] -> "['x', 'y']"
1076 1077 1078
    """
    if args is None: return '[]'
    assert isinstance(args, (list, tuple))
1079 1080
    args = ["{}".format(arg) for arg in args]
    return repr(args)
1081 1082


1083
def _jit_compile(file_path, verbose=False):
1084 1085 1086 1087 1088
    """
    Build shared library in subprocess
    """
    ext_dir = os.path.dirname(file_path)
    setup_file = os.path.basename(file_path)
1089

1090 1091 1092
    # Using interpreter same with current process.
    interpreter = sys.executable

1093 1094
    try:
        py_version = subprocess.check_output([interpreter, '-V'])
T
tianshuo78520a 已提交
1095
        py_version = py_version.decode()
1096
        log_v("Using Python interpreter: {}, version: {}".format(
1097
            interpreter, py_version.strip()), verbose)
1098 1099 1100 1101 1102 1103
    except Exception:
        _, error, _ = sys.exc_info()
        raise RuntimeError(
            'Failed to check Python interpreter with `{}`, errors: {}'.format(
                interpreter, error))

1104 1105 1106 1107 1108 1109 1110
    if IS_WINDOWS:
        compile_cmd = 'cd /d {} && {} {} build'.format(ext_dir, interpreter,
                                                       setup_file)
    else:
        compile_cmd = 'cd {} && {} {} build'.format(ext_dir, interpreter,
                                                    setup_file)

1111 1112
    print("Compiling user custom op, it will cost a few seconds.....")
    run_cmd(compile_cmd, verbose)
1113 1114 1115 1116 1117 1118 1119 1120


def parse_op_name_from(sources):
    """
    Parse registerring custom op name from sources.
    """

    def regex(content):
1121
        pattern = re.compile(r'PD_BUILD_OP\(([^,\)]+)\)')
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
        content = re.sub(r'\s|\t|\n', '', content)
        op_name = pattern.findall(content)
        op_name = set([re.sub('_grad', '', name) for name in op_name])

        return op_name

    op_names = set()
    for source in sources:
        with open(source, 'r') as f:
            content = f.read()
            op_names |= regex(content)

1134
    return list(op_names)
1135 1136


1137
def run_cmd(command, verbose=False):
1138 1139 1140
    """
    Execute command with subprocess.
    """
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
    # logging
    log_v("execute command: {}".format(command), verbose)

    # execute command
    try:
        if verbose:
            return subprocess.check_call(
                command, shell=True, stderr=subprocess.STDOUT)
        else:
            return subprocess.check_call(command, shell=True, stdout=DEVNULL)
    except Exception:
        _, error, _ = sys.exc_info()
        raise RuntimeError("Failed to run command: {}, errors: {}".format(
            compile, error))


def check_abi_compatibility(compiler, verbose=False):
    """
    Check whether GCC version on user local machine is compatible with Paddle in
    site-packages.
    """
1162
    if os.environ.get('PADDLE_SKIP_CHECK_ABI') in ['True', 'true', '1']:
1163 1164
        return True

1165 1166 1167
    if not IS_WINDOWS:
        cmd_out = subprocess.check_output(
            ['which', compiler], stderr=subprocess.STDOUT)
T
tianshuo78520a 已提交
1168
        compiler_path = os.path.realpath(cmd_out.decode()).strip()
1169 1170 1171 1172 1173 1174 1175 1176 1177
        # if not found any suitable compiler, raise warning
        if not any(name in compiler_path
                   for name in _expected_compiler_current_platform()):
            warnings.warn(
                WRONG_COMPILER_WARNING.format(
                    user_compiler=compiler,
                    paddle_compiler=_expected_compiler_current_platform()[0],
                    platform=OS_NAME))
            return False
1178

1179
    version = (0, 0, 0)
1180 1181 1182 1183 1184
    # clang++ have no ABI compatibility problem
    if OS_NAME.startswith('darwin'):
        return True
    try:
        if OS_NAME.startswith('linux'):
1185
            mini_required_version = GCC_MINI_VERSION
1186
            version_info = subprocess.check_output(
1187
                [compiler, '-dumpfullversion', '-dumpversion'])
T
tianshuo78520a 已提交
1188
            version_info = version_info.decode()
1189 1190
            version = version_info.strip().split('.')
        elif IS_WINDOWS:
1191 1192 1193
            mini_required_version = MSVC_MINI_VERSION
            compiler_info = subprocess.check_output(
                compiler, stderr=subprocess.STDOUT)
T
tianshuo78520a 已提交
1194 1195 1196 1197
            try:
                compiler_info = compiler_info.decode('UTF-8')
            except UnicodeDecodeError:
                compiler_info = compiler_info.decode('gbk')
1198 1199 1200
            match = re.search(r'(\d+)\.(\d+)\.(\d+)', compiler_info.strip())
            if match is not None:
                version = match.groups()
1201
    except Exception:
1202
        # check compiler version failed
1203 1204 1205
        _, error, _ = sys.exc_info()
        warnings.warn('Failed to check compiler version for {}: {}'.format(
            compiler, error))
1206
        return False
1207

1208 1209 1210 1211 1212 1213
    # check version compatibility
    assert len(version) == 3
    if tuple(map(int, version)) >= mini_required_version:
        return True
    warnings.warn(
        ABI_INCOMPATIBILITY_WARNING.format(
Z
Zhou Wei 已提交
1214
            user_compiler=compiler, version='.'.join(version)))
1215 1216 1217 1218 1219 1220 1221
    return False


def _expected_compiler_current_platform():
    """
    Returns supported compiler string on current platform
    """
1222 1223 1224 1225 1226 1227
    if OS_NAME.startswith('darwin'):
        expect_compilers = ['clang', 'clang++']
    elif OS_NAME.startswith('linux'):
        expect_compilers = ['gcc', 'g++', 'gnu-c++', 'gnu-cc']
    elif IS_WINDOWS:
        expect_compilers = ['cl']
1228 1229 1230
    return expect_compilers


1231
def log_v(info, verbose=True):
1232 1233 1234 1235
    """
    Print log information on stdout.
    """
    if verbose:
1236
        logger.info(info)