setup.py.in 29.5 KB
Newer Older
Y
Yancey 已提交
1
import subprocess
2
import os
3
import os.path
4
import errno
5
import re
6
import shutil
7
import sys
8
import fnmatch
C
Chengmo 已提交
9
import errno
10
import platform
11

12
from contextlib import contextmanager
13 14 15
from setuptools import Command
from setuptools import setup, Distribution, Extension
from setuptools.command.install import install as InstallCommandBase
16
from setuptools.command.egg_info import egg_info
17 18


19 20 21
class BinaryDistribution(Distribution):
    def has_ext_modules(foo):
        return True
Z
zhangjinchao01 已提交
22

Y
Yancey 已提交
23 24
RC      = 0

25
ext_name = '.dll' if os.name == 'nt' else ('.dylib' if sys.platform == 'darwin' else '.so')
Y
Yancey 已提交
26 27 28 29

def git_commit():
    try:
        cmd = ['git', 'rev-parse', 'HEAD']
30 31
        git_commit = subprocess.Popen(cmd, stdout = subprocess.PIPE,
            cwd="@PADDLE_SOURCE_DIR@").communicate()[0].strip()
Y
Yancey 已提交
32 33
    except:
        git_commit = 'Unknown'
34
    git_commit = git_commit.decode()
35
    return str(git_commit)
Y
Yancey 已提交
36

37
def _get_version_detail(idx):
38 39
    assert idx < 3, "vesion info consists of %(major)d.%(minor)d.%(patch)d, \
        so detail index must less than 3"
40

M
minqiyang 已提交
41 42
    if re.match('@TAG_VERSION_REGEX@', '@PADDLE_VERSION@'):
        version_details = '@PADDLE_VERSION@'.split('.')
43

M
minqiyang 已提交
44
        if len(version_details) >= 3:
M
minqiyang 已提交
45
            return version_details[idx]
46

47
    return 0
48

M
minqiyang 已提交
49
def get_major():
50
    return int(_get_version_detail(0))
51

M
minqiyang 已提交
52
def get_minor():
53
    return int(_get_version_detail(1))
54

55
def get_patch():
56
    return str(_get_version_detail(2))
57

58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
def get_cuda_version():
    if '@WITH_GPU@' == 'ON':
        return '@CUDA_VERSION@'
    else:
        return 'False'

def get_cudnn_version():
    if '@WITH_GPU@' == 'ON':
        temp_cudnn_version = ''
        if '@CUDNN_MAJOR_VERSION@':
            temp_cudnn_version += '@CUDNN_MAJOR_VERSION@'
            if '@CUDNN_MINOR_VERSION@':
                temp_cudnn_version += '.@CUDNN_MINOR_VERSION@'
                if '@CUDNN_PATCHLEVEL_VERSION@':
                    temp_cudnn_version += '.@CUDNN_PATCHLEVEL_VERSION@'
        return temp_cudnn_version
    else:
        return 'False'

77
def is_taged():
M
minqiyang 已提交
78
    try:
79
        cmd = ['git', 'describe', '--exact-match', '--tags', 'HEAD', '2>/dev/null']
80
        git_tag = subprocess.Popen(cmd, stdout = subprocess.PIPE, cwd="@PADDLE_SOURCE_DIR@").communicate()[0].strip()
81
        git_tag = git_tag.decode()
M
minqiyang 已提交
82
    except:
83 84
        return False

85
    if str(git_tag).replace('v', '') == '@PADDLE_VERSION@':
86 87
        return True
    else:
M
minqiyang 已提交
88
        return False
89

90
def write_version_py(filename='paddle/version/__init__.py'):
91
    cnt = '''# THIS FILE IS GENERATED FROM PADDLEPADDLE SETUP.PY
Y
Yancey 已提交
92
#
93
full_version    = '%(major)d.%(minor)d.%(patch)s'
Y
Yancey 已提交
94 95
major           = '%(major)d'
minor           = '%(minor)d'
96
patch           = '%(patch)s'
Y
Yancey 已提交
97
rc              = '%(rc)d'
98 99
cuda_version    = '%(cuda)s'
cudnn_version   = '%(cudnn)s'
Y
Yancey 已提交
100 101
istaged         = %(istaged)s
commit          = '%(commit)s'
L
Luo Tao 已提交
102
with_mkl        = '%(with_mkl)s'
Y
Yancey 已提交
103

104
__all__ = ['cuda', 'cudnn', 'show']
105

Y
Yancey 已提交
106
def show():
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 147
    """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
    
    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'

            # Case 2: paddle is not tagged
            paddle.version.show()
            # commit: cfa357e984bfd2ffa16820e354020529df434f7d
            # cuda: '10.2'
            # cudnn: '7.6.5'
    """
Y
Yancey 已提交
148
    if istaged:
149 150 151 152 153
        print('full_version:', full_version)
        print('major:', major)
        print('minor:', minor)
        print('patch:', patch)
        print('rc:', rc)
Y
Yancey 已提交
154
    else:
155
        print('commit:', commit)
156 157
    print('cuda:', cuda_version)
    print('cudnn:', cudnn_version)
L
Luo Tao 已提交
158 159 160

def mkl():
    return with_mkl
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

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
Y
Yancey 已提交
195 196
'''
    commit = git_commit()
197 198 199 200 201 202 203 204 205

    dirname = os.path.dirname(filename)

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

Y
Yancey 已提交
206 207
    with open(filename, 'w') as f:
        f.write(cnt % {
208 209 210
            'major': get_major(),
            'minor': get_minor(),
            'patch': get_patch(),
Y
Yancey 已提交
211 212
            'rc': RC,
            'version': '${PADDLE_VERSION}',
213 214
            'cuda': get_cuda_version(),
            'cudnn': get_cudnn_version(),
Y
Yancey 已提交
215
            'commit': commit,
216
            'istaged': is_taged(),
L
Luo Tao 已提交
217
            'with_mkl': '@WITH_MKL@'})
Y
Yancey 已提交
218

219
write_version_py(filename='@PADDLE_BINARY_DIR@/python/paddle/version/__init__.py')
Y
Yancey 已提交
220

221 222 223 224 225 226 227 228 229 230 231 232 233 234
def write_cuda_env_config_py(filename='paddle/cuda_env.py'):
    cnt = ""
    if '${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)

write_cuda_env_config_py(filename='@PADDLE_BINARY_DIR@/python/paddle/cuda_env.py')

C
Chengmo 已提交
235
def write_distributed_training_mode_py(filename='paddle/fluid/incubate/fleet/parameter_server/version.py'):
236
    cnt = '''
C
Chengmo 已提交
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

# THIS FILE IS GENERATED FROM PADDLEPADDLE SETUP.PY

from paddle.fluid.incubate.fleet.base.mode import Mode

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 '${WITH_PSLIB}' == 'ON' else 'TRANSPILER'
        })

write_distributed_training_mode_py(filename='@PADDLE_BINARY_DIR@/python/paddle/fluid/incubate/fleet/parameter_server/version.py')
Y
Yancey 已提交
263

264

Z
zhangjinchao01 已提交
265
packages=['paddle',
266
          'paddle.libs',
Q
qiaolongfei 已提交
267
          'paddle.utils',
268
          'paddle.utils.gast',
269
          'paddle.utils.cpp_extension',
270 271
          'paddle.dataset',
          'paddle.reader',
272
          'paddle.distributed',
273 274
          'paddle.distributed.communication',
          'paddle.distributed.communication.stream',
275
          'paddle.distributed.metric',
Z
ziyoujiyi 已提交
276 277
          'paddle.distributed.ps',
          'paddle.distributed.ps.utils',
278
          'paddle.incubate',
279
          'paddle.incubate.autograd',
280
          'paddle.incubate.optimizer',
281
          'paddle.incubate.checkpoint',
282
          'paddle.incubate.operators',
283
          'paddle.incubate.tensor',
Z
Zhong Hui 已提交
284
          'paddle.incubate.multiprocessing',
285
          'paddle.incubate.nn',
286
          'paddle.incubate.asp',
W
wuhuanzhou 已提交
287
          'paddle.incubate.passes',
288
          'paddle.distribution',
R
Roc 已提交
289
          'paddle.distributed.utils',
B
Baibaifan 已提交
290
          'paddle.distributed.sharding',
291
          'paddle.distributed.fleet',
292 293 294 295 296 297
          'paddle.distributed.launch',
          'paddle.distributed.launch.context',
          'paddle.distributed.launch.controllers',
          'paddle.distributed.launch.job',
          'paddle.distributed.launch.plugins',
          'paddle.distributed.launch.utils',
298
          'paddle.distributed.fleet.base',
299
          'paddle.distributed.fleet.recompute',
K
kuizhiqing 已提交
300
          'paddle.distributed.fleet.elastic',
301
          'paddle.distributed.fleet.meta_optimizers',
302
          'paddle.distributed.fleet.meta_optimizers.sharding',
303
          'paddle.distributed.fleet.meta_optimizers.ascend',
304
          'paddle.distributed.fleet.meta_optimizers.dygraph_optimizer',
305
          'paddle.distributed.fleet.runtime',
306
          'paddle.distributed.rpc',
307
          'paddle.distributed.fleet.dataset',
308
          'paddle.distributed.fleet.data_generator',
309 310 311
          'paddle.distributed.fleet.metrics',
          'paddle.distributed.fleet.proto',
          'paddle.distributed.fleet.utils',
W
wuhuachaocoding 已提交
312 313
          'paddle.distributed.fleet.layers',
          'paddle.distributed.fleet.layers.mpu',
314
          'paddle.distributed.fleet.meta_parallel',
315
          'paddle.distributed.fleet.meta_parallel.pp_utils',
B
Baibaifan 已提交
316
          'paddle.distributed.fleet.meta_parallel.sharding',
317
          'paddle.distributed.fleet.meta_parallel.parallel_layers',
318
          'paddle.distributed.auto_parallel',
319
          'paddle.distributed.auto_parallel.operators',
320
          'paddle.distributed.auto_parallel.tuner',
321
          'paddle.distributed.auto_parallel.cost',
322
          'paddle.distributed.passes',
R
Roc 已提交
323 324
          'paddle.distributed.models',
          'paddle.distributed.models.moe',
325
          'paddle.framework',
326
          'paddle.jit',
327
          'paddle.jit.dy2static',
W
Wilber 已提交
328
          'paddle.inference',
329 330
          'paddle.inference.contrib',
          'paddle.inference.contrib.utils',
331
          'paddle.fluid',
W
Wilber 已提交
332
          'paddle.fluid.inference',
L
lujun 已提交
333
          'paddle.fluid.dygraph',
334
          'paddle.fluid.dygraph.dygraph_to_static',
335
          'paddle.fluid.dygraph.amp',
336
          'paddle.fluid.proto',
X
Xin Pan 已提交
337
          'paddle.fluid.proto.profiler',
H
heqiaozhi 已提交
338
          'paddle.fluid.distributed',
Y
Yancey 已提交
339
          'paddle.fluid.layers',
340
          'paddle.fluid.dataloader',
Q
Qingsheng Li 已提交
341 342
          'paddle.fluid.contrib',
          'paddle.fluid.contrib.decoder',
D
Dang Qingqing 已提交
343
          'paddle.fluid.contrib.quantize',
W
whs 已提交
344
          'paddle.fluid.contrib.slim',
W
WangZhen 已提交
345
          'paddle.fluid.contrib.slim.quantization',
346
          'paddle.fluid.contrib.slim.quantization.imperative',
C
chengduo 已提交
347
          'paddle.fluid.contrib.extend_optimizer',
348
          'paddle.fluid.contrib.mixed_precision',
349
          'paddle.fluid.contrib.mixed_precision.bf16',
350
          'paddle.fluid.contrib.layers',
351
          'paddle.fluid.contrib.sparsity',
Q
qiaolongfei 已提交
352
          'paddle.fluid.transpiler',
D
dongdaxiang 已提交
353 354
          'paddle.fluid.transpiler.details',
          'paddle.fluid.incubate',
355
          'paddle.fluid.incubate.data_generator',
D
dongdaxiang 已提交
356
          'paddle.fluid.incubate.fleet',
357
          'paddle.fluid.incubate.checkpoint',
D
dongdaxiang 已提交
358 359
          'paddle.fluid.incubate.fleet.base',
          'paddle.fluid.incubate.fleet.parameter_server',
T
tangwei12 已提交
360
          'paddle.fluid.incubate.fleet.parameter_server.distribute_transpiler',
361
          'paddle.fluid.incubate.fleet.parameter_server.pslib',
362
          'paddle.fluid.incubate.fleet.parameter_server.ir',
363
          'paddle.fluid.incubate.fleet.collective',
364
          'paddle.fluid.incubate.fleet.utils',
365
          'paddle.amp',
H
huangxu96 已提交
366
          'paddle.cost_model',
367 368 369 370 371
          'paddle.hapi',
          'paddle.vision',
          'paddle.vision.models',
          'paddle.vision.transforms',
          'paddle.vision.datasets',
372
          'paddle.audio',
373 374 375 376
	      'paddle.audio.functional',
	      'paddle.audio.features',
	      'paddle.audio.datasets',
	      'paddle.audio.backends',
377 378
          'paddle.text',
          'paddle.text.datasets',
H
hong 已提交
379
          'paddle.incubate',
380 381 382
          'paddle.incubate.nn',
          'paddle.incubate.nn.functional',
          'paddle.incubate.nn.layer',
383
          'paddle.incubate.optimizer.functional',
384
          'paddle.incubate.autograd',
R
Roc 已提交
385
          'paddle.incubate.distributed',
386
          'paddle.incubate.distributed.fleet',
R
Roc 已提交
387 388 389
          'paddle.incubate.distributed.models',
          'paddle.incubate.distributed.models.moe',
          'paddle.incubate.distributed.models.moe.gate',
390 391 392 393
          'paddle.sparse',
          'paddle.sparse.nn',
          'paddle.sparse.nn.layer',
          'paddle.sparse.nn.functional',
394
          'paddle.incubate.xpu',
395
          'paddle.io',
H
hong 已提交
396
          'paddle.optimizer',
397 398
          'paddle.nn',
          'paddle.nn.functional',
399
          'paddle.nn.layer',
400
          'paddle.nn.quant',
H
hong 已提交
401
          'paddle.nn.initializer',
402
          'paddle.nn.utils',
H
hong 已提交
403
          'paddle.metric',
404 405
          'paddle.static',
          'paddle.static.nn',
406
          'paddle.static.amp',
407
          'paddle.static.sparsity',
408
          'paddle.tensor',
C
channings 已提交
409
          'paddle.onnx',
410
          'paddle.autograd',
411 412
          'paddle.device',
          'paddle.device.cuda',
413
          'paddle.version',
414
          'paddle.profiler',
415 416
          'paddle.geometric',
          'paddle.geometric.message_passing',
417
          'paddle.geometric.sampling',
418
          ]
L
Luo Tao 已提交
419

420 421
with open('@PADDLE_SOURCE_DIR@/python/requirements.txt') as f:
    setup_requires = f.read().splitlines()
422

R
Roc 已提交
423 424 425
if sys.version_info < (3,7):
    raise RuntimeError("Paddle only support Python version>=3.7 now")

426 427 428 429 430 431 432 433
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

434
# the prefix is sys.prefix which should always be usr
L
Luo Tao 已提交
435
paddle_bins = ''
436

T
Tao Luo 已提交
437 438
if not '${WIN32}':
    paddle_bins = ['${PADDLE_BINARY_DIR}/paddle/scripts/paddle']
439 440 441 442 443 444

if os.name != 'nt':
    package_data={'paddle.fluid': ['${FLUID_CORE_NAME}' + '.so']}
else:
    package_data={'paddle.fluid': ['${FLUID_CORE_NAME}' + '.pyd', '${FLUID_CORE_NAME}' + '.lib']}

H
huangxu96 已提交
445
package_data['paddle.fluid'] += ['${PADDLE_BINARY_DIR}/python/paddle/cost_model/static_op_benchmark.json']
P
peizhilin 已提交
446

L
Luo Tao 已提交
447
package_dir={
448
    '': '${PADDLE_BINARY_DIR}/python',
L
Luo Tao 已提交
449 450 451 452
    # The paddle.fluid.proto will be generated while compiling.
    # So that package points to other directory.
    'paddle.fluid.proto.profiler': '${PADDLE_BINARY_DIR}/paddle/fluid/platform',
    'paddle.fluid.proto': '${PADDLE_BINARY_DIR}/paddle/fluid/framework',
Q
qiaolongfei 已提交
453
    'paddle.fluid': '${PADDLE_BINARY_DIR}/python/paddle/fluid',
L
Luo Tao 已提交
454
}
455

456 457
# put all thirdparty libraries in paddle.libs
libs_path='${PADDLE_BINARY_DIR}/python/paddle/libs'
P
peizhilin 已提交
458

P
peizhilin 已提交
459
package_data['paddle.libs']= []
P
peizhilin 已提交
460
package_data['paddle.libs']=[('libwarpctc' if os.name != 'nt' else 'warpctc') + ext_name]
P
peizhilin 已提交
461
shutil.copy('${WARPCTC_LIBRARIES}', libs_path)
P
peizhilin 已提交
462

463 464 465 466 467 468 469 470 471 472 473 474 475
package_data['paddle.libs']+=[
    os.path.basename('${LAPACK_LIB}'), 
    os.path.basename('${BLAS_LIB}'),
    os.path.basename('${GFORTRAN_LIB}'),
    os.path.basename('${GNU_RT_LIB_1}')]
shutil.copy('${BLAS_LIB}', libs_path)
shutil.copy('${LAPACK_LIB}', libs_path)
shutil.copy('${GFORTRAN_LIB}', libs_path)
shutil.copy('${GNU_RT_LIB_1}', libs_path)
if not sys.platform.startswith("linux"):
    package_data['paddle.libs']+=[os.path.basename('${GNU_RT_LIB_2}')]
    shutil.copy('${GNU_RT_LIB_2}', libs_path)

476
if '${WITH_MKL}' == 'ON':
P
peizhilin 已提交
477 478 479
    shutil.copy('${MKLML_SHARED_LIB}', libs_path)
    shutil.copy('${MKLML_SHARED_IOMP_LIB}', libs_path)
    package_data['paddle.libs']+=[('libmklml_intel' if os.name != 'nt' else 'mklml') + ext_name, ('libiomp5' if os.name != 'nt' else 'libiomp5md') + ext_name]
P
peizhilin 已提交
480 481
else:
    if os.name == 'nt':
P
peizhilin 已提交
482
        # copy the openblas.dll
483
        shutil.copy('${OPENBLAS_SHARED_LIB}', libs_path)
P
peizhilin 已提交
484
        package_data['paddle.libs'] += ['openblas' + ext_name]
W
Wilber 已提交
485
    elif os.name == 'posix' and platform.machine() == 'aarch64' and '${OPENBLAS_LIB}'.endswith('so'):
H
houj04 已提交
486
        # copy the libopenblas.so on linux+aarch64
487
        # special: libpaddle.so without avx depends on 'libopenblas.so.0', not 'libopenblas.so'
W
Wilber 已提交
488 489 490
        if os.path.exists('${OPENBLAS_LIB}' + '.0'):
            shutil.copy('${OPENBLAS_LIB}' + '.0', libs_path)
            package_data['paddle.libs'] += ['libopenblas.so.0']
P
peizhilin 已提交
491

492 493 494
if '${WITH_LITE}' == 'ON':
    shutil.copy('${LITE_SHARED_LIB}', libs_path)
    package_data['paddle.libs']+=['libpaddle_full_api_shared' + ext_name]
495 496 497 498 499 500
    if '${LITE_WITH_NNADAPTER}' == 'ON':
        shutil.copy('${LITE_NNADAPTER_LIB}', libs_path)
        package_data['paddle.libs']+=['libnnadapter' + ext_name]
        if '${NNADAPTER_WITH_HUAWEI_ASCEND_NPU}' == 'ON':
            shutil.copy('${LITE_NNADAPTER_NPU_LIB}', libs_path)
            package_data['paddle.libs']+=['libnnadapter_driver_huawei_ascend_npu' + ext_name]
501

502 503
if '${WITH_CINN}' == 'ON':
    shutil.copy('${CINN_LIB_LOCATION}/${CINN_LIB_NAME}', libs_path)
504
    shutil.copy('${CINN_INCLUDE_DIR}/cinn/runtime/cuda/cinn_cuda_runtime_source.cuh', libs_path)
505
    package_data['paddle.libs']+=['libcinnapi.so']
506
    package_data['paddle.libs']+=['cinn_cuda_runtime_source.cuh']
507 508 509 510
    if '${CMAKE_BUILD_TYPE}' == 'Release' and os.name != 'nt':
        command = "patchelf --set-rpath '$ORIGIN/' %s/${CINN_LIB_NAME}" % libs_path
        if os.system(command) != 0:
            raise Exception("patch %s/${CINN_LIB_NAME} failed, command: %s" % (libs_path, command))
511

X
xujiaqi01 已提交
512 513
if '${WITH_PSLIB}' == 'ON':
    shutil.copy('${PSLIB_LIB}', libs_path)
X
xujiaqi01 已提交
514 515
    if os.path.exists('${PSLIB_VERSION_PY}'):
        shutil.copy('${PSLIB_VERSION_PY}', '${PADDLE_BINARY_DIR}/python/paddle/fluid/incubate/fleet/parameter_server/pslib/')
X
xujiaqi01 已提交
516 517
    package_data['paddle.libs'] += ['libps' + ext_name]

S
Sang Ik Lee 已提交
518
if '${WITH_MKLDNN}' == 'ON':
P
peizhilin 已提交
519
    if '${CMAKE_BUILD_TYPE}' == 'Release' and os.name != 'nt':
P
peizhilin 已提交
520 521 522 523
        # only change rpath in Release mode.
        # TODO(typhoonzero): use install_name_tool to patch mkl libs once
        # we can support mkl on mac.
        #
A
Adam 已提交
524
        # change rpath of libdnnl.so.1, add $ORIGIN/ to it.
P
peizhilin 已提交
525
        # The reason is that all thirdparty libraries in the same directory,
A
Adam 已提交
526
        # thus, libdnnl.so.1 will find libmklml_intel.so and libiomp5.so.
P
peizhilin 已提交
527 528
        command = "patchelf --set-rpath '$ORIGIN/' ${MKLDNN_SHARED_LIB}"
        if os.system(command) != 0:
A
Adam 已提交
529
            raise Exception("patch libdnnl.so failed, command: %s" % command)
S
Sang Ik Lee 已提交
530
    shutil.copy('${MKLDNN_SHARED_LIB}', libs_path)
A
Adam 已提交
531 532
    if os.name != 'nt':
        shutil.copy('${MKLDNN_SHARED_LIB_1}', libs_path)
533 534
        shutil.copy('${MKLDNN_SHARED_LIB_2}', libs_path)
        package_data['paddle.libs']+=['libmkldnn.so.0', 'libdnnl.so.1', 'libdnnl.so.2']
A
Adam 已提交
535 536 537
    else:
        package_data['paddle.libs']+=['mkldnn.dll']

538 539
if '${WITH_ONNXRUNTIME}' == 'ON':
    shutil.copy('${ONNXRUNTIME_SHARED_LIB}', libs_path)
540
    shutil.copy('${PADDLE2ONNX_LIB}', libs_path)
541 542 543
    if os.name == 'nt':
        package_data['paddle.libs']+=['paddle2onnx.dll', 'onnxruntime.dll']
    else:
H
heliqi 已提交
544
        package_data['paddle.libs']+=['${PADDLE2ONNX_LIB_NAME}', '${ONNXRUNTIME_LIB_NAME}']
545

546 547 548 549 550 551 552 553 554 555 556 557 558
if '${WITH_XPU}' == 'ON':
    # only change rpath in Release mode,
    if '${CMAKE_BUILD_TYPE}' == 'Release':
        if os.name != 'nt':
            if "@APPLE@" == "1":
                command = "install_name_tool -id \"@loader_path/\" ${XPU_API_LIB}"
            else:
                command = "patchelf --set-rpath '$ORIGIN/' ${XPU_API_LIB}"
            if os.system(command) != 0:
                raise Exception("patch ${XPU_API_LIB} failed, command: %s" % command)
    shutil.copy('${XPU_API_LIB}', libs_path)
    shutil.copy('${XPU_RT_LIB}', libs_path)
    package_data['paddle.libs']+=['${XPU_API_LIB_NAME}',
559
                                  '${XPU_RT_LIB_NAME}']
560

561 562 563 564
if '${WITH_XPU_BKCL}' == 'ON':
    shutil.copy('${XPU_BKCL_LIB}', libs_path)
    package_data['paddle.libs']+=['${XPU_BKCL_LIB_NAME}']

565
# remove unused paddle/libs/__init__.py
P
peizhilin 已提交
566 567
if os.path.isfile(libs_path+'/__init__.py'):
    os.remove(libs_path+'/__init__.py')
568 569
package_dir['paddle.libs']=libs_path

570

571
# change rpath of ${FLUID_CORE_NAME}.ext, add $ORIGIN/../libs/ to it.
572
# The reason is that libwarpctc.ext, libiomp5.ext etc are in paddle.libs, and
573
# ${FLUID_CORE_NAME}.ext is in paddle.fluid, thus paddle/fluid/../libs will pointer to above libraries.
574
# This operation will fix https://github.com/PaddlePaddle/Paddle/issues/3213
L
luotao1 已提交
575
if '${CMAKE_BUILD_TYPE}' == 'Release':
P
peizhilin 已提交
576
    if os.name != 'nt':
577
        # only change rpath in Release mode, since in Debug mode, ${FLUID_CORE_NAME}.xx is too large to be changed.
L
luotao1 已提交
578
        if "@APPLE@" == "1":
579 580
            commands = ["install_name_tool -id '@loader_path/../libs/' ${PADDLE_BINARY_DIR}/python/paddle/fluid/${FLUID_CORE_NAME}" + '.so']
            commands.append("install_name_tool -add_rpath '@loader_path/../libs/' ${PADDLE_BINARY_DIR}/python/paddle/fluid/${FLUID_CORE_NAME}" + '.so')
L
luotao1 已提交
581
        else:
582
            commands = ["patchelf --set-rpath '$ORIGIN/../libs/' ${PADDLE_BINARY_DIR}/python/paddle/fluid/${FLUID_CORE_NAME}" + '.so']
W
Wilber 已提交
583
        # The sw_64 not suppot patchelf, so we just disable that.
H
houj04 已提交
584
        if platform.machine() != 'sw_64' and platform.machine() != 'mips64':
585 586 587
            for command in commands:
                if os.system(command) != 0:
                    raise Exception("patch ${FLUID_CORE_NAME}.%s failed, command: %s" % (ext_name, command))
P
peizhilin 已提交
588

P
peizhilin 已提交
589
ext_modules = [Extension('_foo', ['stub.cc'])]
P
peizhilin 已提交
590 591 592 593 594 595
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
P
peizhilin 已提交
596
    ext_modules = []
597 598
elif sys.platform == 'darwin':
    ext_modules = []
T
tensor-tang 已提交
599

600
def find_files(pattern, root, recursive=False):
601
    for dirpath, _, files in os.walk(root):
602 603 604 605
        for filename in fnmatch.filter(files, pattern):
            yield os.path.join(dirpath, filename)
        if not recursive:
            break
606 607

headers = (
608
    # paddle level api headers
609
    list(find_files('*.h', '@PADDLE_SOURCE_DIR@/paddle')) +
610
    list(find_files('*.h', '@PADDLE_SOURCE_DIR@/paddle/phi/api')) +  # phi unify api header
611
    list(find_files('*.h', '@PADDLE_SOURCE_DIR@/paddle/phi/api/ext')) +  # custom op api
612 613 614
    list(find_files('*.h', '@PADDLE_SOURCE_DIR@/paddle/phi/api/include')) +  # phi api
    list(find_files('*.h', '@PADDLE_SOURCE_DIR@/paddle/phi/common')) +  # phi common headers
    # phi level api headers (low level api)
615 616
    list(find_files('*.h', '@PADDLE_SOURCE_DIR@/paddle/phi')) +  # phi extension header
    list(find_files('*.h', '@PADDLE_SOURCE_DIR@/paddle/phi/include', recursive=True)) +  # phi include headers
617
    list(find_files('*.h', '@PADDLE_SOURCE_DIR@/paddle/phi/backends', recursive=True)) +  # phi backends headers
618 619
    list(find_files('*.h', '@PADDLE_SOURCE_DIR@/paddle/phi/core', recursive=True)) +  # phi core headers
    list(find_files('*.h', '@PADDLE_SOURCE_DIR@/paddle/phi/infermeta', recursive=True)) +  # phi infermeta headers
620 621 622 623 624
    list(find_files('*.h', '@PADDLE_SOURCE_DIR@/paddle/phi/kernels')) +  # phi kernels headers
    list(find_files('*.h', '@PADDLE_SOURCE_DIR@/paddle/phi/kernels/sparse')) +  # phi sparse kernels headers
    list(find_files('*.h', '@PADDLE_SOURCE_DIR@/paddle/phi/kernels/selected_rows')) +  # phi selected_rows kernels headers
    list(find_files('*.h', '@PADDLE_SOURCE_DIR@/paddle/phi/kernels/strings')) +  # phi sparse kernels headers
    list(find_files('*.h', '@PADDLE_SOURCE_DIR@/paddle/phi/kernels/primitive')) +  # phi kernel primitive api headers
625 626
    # capi headers
    list(find_files('*.h', '@PADDLE_SOURCE_DIR@/paddle/phi/capi', recursive=True)) +  # phi capi headers
627 628
    # profiler headers
    list(find_files('trace_event.h', '@PADDLE_SOURCE_DIR@/paddle/fluid/platform/profiler')) +  # phi profiler headers
629 630 631
    # utils api headers
    list(find_files('*.h', '@PADDLE_SOURCE_DIR@/paddle/utils', recursive=True))) # paddle utils headers

632
jit_layer_headers = ['layer.h', 'serializer.h', 'serializer_utils.h', 'all.h', 'function.h']
633
for f in jit_layer_headers:
634
    headers += list(find_files(f, '@PADDLE_SOURCE_DIR@/paddle/fluid/jit', recursive=True))
635

636 637 638
if '${WITH_MKLDNN}' == 'ON':
    headers += list(find_files('*', '${MKLDNN_INSTALL_DIR}/include')) # mkldnn

639
if '${WITH_GPU}' == 'ON' or '${WITH_ROCM}' == 'ON':
640 641
    # externalErrorMsg.pb for External Error message
    headers += list(find_files('*.pb', '${externalError_INCLUDE_DIR}'))
642 643 644 645 646

class InstallCommand(InstallCommandBase):
    def finalize_options(self):
        ret = InstallCommandBase.finalize_options(self)
        self.install_lib = self.install_platlib
647
        self.install_headers = os.path.join(self.install_platlib, 'paddle', 'include')
648
        return ret
649

650 651 652 653
class InstallHeaders(Command):
    """Override how headers are copied.
    """
    description = 'install C/C++ header files'
654

655 656 657 658 659
    user_options = [('install-dir=', 'd',
                     'directory to install header files to'),
                    ('force', 'f',
                     'force installation (overwrite existing files)'),
                   ]
660

661
    boolean_options = ['force']
662

663 664 665 666
    def initialize_options(self):
        self.install_dir = None
        self.force = 0
        self.outfiles = []
667

668 669 670 671
    def finalize_options(self):
        self.set_undefined_options('install',
                                   ('install_headers', 'install_dir'),
                                   ('force', 'force'))
672

673 674 675 676
    def mkdir_and_copy_file(self, header):
        if 'pb.h' in header:
            install_dir = re.sub('${PADDLE_BINARY_DIR}/', '', header)
        elif 'third_party' not in header:
677
            # paddle headers
678
            install_dir = re.sub('@PADDLE_SOURCE_DIR@/', '', header)
679 680 681 682
            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)
683 684 685
            if 'trace_event.h' in install_dir:
                install_dir = re.sub('fluid/platform/profiler', 'phi/backends/custom', install_dir)
                print('trace_event.h install_dir: ', install_dir)
686 687 688
        else:
            # third_party
            install_dir = re.sub('${THIRD_PARTY_PATH}', 'third_party', header)
689
            patterns = ['install/mkldnn/include']
690 691
            for pattern in patterns:
                install_dir = re.sub(pattern, '', install_dir)
692 693 694 695
        install_dir = os.path.join(self.install_dir, os.path.dirname(install_dir))
        if not os.path.exists(install_dir):
            self.mkpath(install_dir)
        return self.copy_file(header, install_dir)
696

697 698 699 700 701 702 703 704
    def run(self):
        hdrs = self.distribution.headers
        if not hdrs:
            return
        self.mkpath(self.install_dir)
        for header in hdrs:
            (out, _) = self.mkdir_and_copy_file(header)
            self.outfiles.append(out)
705

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

709 710 711
    def get_outputs(self):
        return self.outfiles

712 713 714 715 716 717 718 719 720 721 722
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("@PADDLE_SOURCE_DIR@/LICENSE", self.egg_info)

        egg_info.run(self)

723 724 725 726
# we redirect setuptools log for non-windows
if sys.platform != 'win32':
    @contextmanager
    def redirect_stdout():
727 728 729 730 731 732 733
        f_log = open('${SETUP_LOG_FILE}', 'w')
        origin_stdout = sys.stdout
        sys.stdout = f_log
        yield
        f_log = sys.stdout
        sys.stdout = origin_stdout
        f_log.close()
734 735 736 737 738
else:
    @contextmanager
    def redirect_stdout():
        yield

739
# Log for PYPI
740 741
with open("@PADDLE_BINARY_DIR@/python/paddle/README.rst", "r", encoding='UTF-8') as f:
    long_description = f.read()
742

W
wuhuanzhou 已提交
743 744 745 746 747 748
# strip *.so to reduce package size
if '${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)

749 750 751 752
with redirect_stdout():
    setup(name='${PACKAGE_NAME}',
        version='${PADDLE_VERSION}',
        description='Parallel Distributed Deep Learning',
753 754 755 756 757 758 759 760 761 762
        long_description=long_description,
        long_description_content_type="text/markdown",
        author_email="Paddle-better@baidu.com",
        maintainer="PaddlePaddle",
        maintainer_email="Paddle-better@baidu.com",
        project_urls = {
            'Homepage': 'https://www.paddlepaddle.org.cn/',
            'Downloads': 'https://github.com/paddlepaddle/paddle'
        }, 
        license='Apache Software License',
763
        packages=packages,
764
        install_requires=setup_requires,
765 766 767 768 769 770 771 772 773
        ext_modules=ext_modules,
        package_data=package_data,
        package_dir=package_dir,
        scripts=paddle_bins,
        distclass=BinaryDistribution,
        headers=headers,
        cmdclass={
            'install_headers': InstallHeaders,
            'install': InstallCommand,
774
            'egg_info': EggInfo,
775 776 777
        },
        entry_points={
            'console_scripts': [
778
                'fleetrun = paddle.distributed.launch.main:launch'
779
            ]
780 781 782 783 784 785 786 787 788 789 790 791 792 793 794
        },
        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 :: 2.7',
            'Programming Language :: Python :: 3.5',
            'Programming Language :: Python :: 3.6',
            'Programming Language :: Python :: 3.7',
            'Programming Language :: Python :: 3.8',
        ],
795 796
    )

797
# As there are a lot of files in purelib which causes many logs,
798
# we don't print them on the screen, and you can open `setup.py.log`
799
# for the full logs.
800 801
if os.path.exists('${SETUP_LOG_FILE}'):
    os.system('grep -v "purelib" ${SETUP_LOG_FILE}')