__init__.py 8.0 KB
Newer Older
1 2
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
# 
3 4 5
# 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
6
# 
7
#     http://www.apache.org/licenses/LICENSE-2.0
8
# 
9 10 11 12 13 14
# 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.

15
# TODO: define the functions to manipulate devices 
16
import re
T
taixiurong 已提交
17
import os
18 19
from paddle.fluid import core
from paddle.fluid import framework
20
from paddle.fluid.dygraph.parallel import ParallelEnv
21
from paddle.fluid.framework import is_compiled_with_cinn  # noqa: F401
22 23
from paddle.fluid.framework import is_compiled_with_cuda  # noqa: F401
from paddle.fluid.framework import is_compiled_with_rocm  # noqa: F401
24
from . import cuda
25

26
__all__ = [  # noqa
27
    'get_cudnn_version',
28
    'set_device',
29 30
    'get_device',
    'XPUPlace',
W
Wenyu 已提交
31
    'is_compiled_with_xpu',
32
    'is_compiled_with_cinn',
33
    'is_compiled_with_cuda',
34
    'is_compiled_with_rocm',
35
    'is_compiled_with_npu'
36 37
]

38 39 40
_cudnn_version = None


41 42
# TODO: WITH_ASCEND_CL may changed to WITH_NPU or others in the future
# for consistent.
43 44
def is_compiled_with_npu():
    """
45
    Whether paddle was built with WITH_ASCEND_CL=ON to support Ascend NPU.
46 47 48 49 50 51 52

    Returns (bool): `True` if NPU is supported, otherwise `False`.

    Examples:
        .. code-block:: python

            import paddle
53
            support_npu = paddle.device.is_compiled_with_npu()
54 55 56 57
    """
    return core.is_compiled_with_npu()


58 59 60 61 62 63 64 65 66 67
def is_compiled_with_xpu():
    """
    Whether paddle was built with WITH_XPU=ON to support Baidu Kunlun

    Returns (bool): whether paddle was built with WITH_XPU=ON

    Examples:
        .. code-block:: python

            import paddle
68
            support_xpu = paddle.device.is_compiled_with_xpu()
69 70 71 72 73 74 75 76 77 78 79 80 81
    """
    return core.is_compiled_with_xpu()


def XPUPlace(dev_id):
    """
    Return a Baidu Kunlun Place

    Parameters:
        dev_id(int): Baidu Kunlun device id

    Examples:
        .. code-block:: python
82

83 84
            # required: xpu
            
85
            import paddle
86
            place = paddle.device.XPUPlace(0)
87 88 89 90
    """
    return core.XPUPlace(dev_id)


91 92 93 94 95 96 97 98 99 100 101 102 103
def get_cudnn_version():
    """
    This funciton return the version of cudnn. the retuen value is int which represents the 
    cudnn version. For example, if it return 7600, it represents the version of cudnn is 7.6.
    
    Returns:
        int: A int value which represents the cudnn version. If cudnn version is not installed, it return None.

    Examples:
        .. code-block:: python
            
            import paddle

104
            cudnn_version = paddle.device.get_cudnn_version()
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121



    """
    global _cudnn_version
    if not core.is_compiled_with_cuda():
        return None
    if _cudnn_version is None:
        cudnn_version = int(core.cudnn_version())
        _cudnn_version = cudnn_version
        if _cudnn_version < 0:
            return None
        else:
            return cudnn_version
    else:
        return _cudnn_version

122

C
chentianyu03 已提交
123
def _convert_to_place(device):
124 125 126
    lower_device = device.lower()
    if lower_device == 'cpu':
        place = core.CPUPlace()
127 128
    elif lower_device == 'gpu':
        if not core.is_compiled_with_cuda():
129 130
            raise ValueError("The device should not be 'gpu', "
                             "since PaddlePaddle is not compiled with CUDA")
131
        place = core.CUDAPlace(ParallelEnv().dev_id)
132 133
    elif lower_device == 'xpu':
        if not core.is_compiled_with_xpu():
134 135
            raise ValueError("The device should not be 'xpu', "
                             "since PaddlePaddle is not compiled with XPU")
T
taixiurong 已提交
136 137 138
        selected_xpus = os.getenv("FLAGS_selected_xpus", "0").split(",")
        device_id = int(selected_xpus[0])
        place = core.XPUPlace(device_id)
H
houj04 已提交
139 140 141 142 143 144 145
    elif lower_device == 'npu':
        if not core.is_compiled_with_npu():
            raise ValueError("The device should not be 'npu', "
                             "since PaddlePaddle is not compiled with NPU")
        selected_npus = os.getenv("FLAGS_selected_npus", "0").split(",")
        device_id = int(selected_npus[0])
        place = core.NPUPlace(device_id)
146
    else:
147 148
        avaliable_gpu_device = re.match(r'gpu:\d+', lower_device)
        avaliable_xpu_device = re.match(r'xpu:\d+', lower_device)
H
houj04 已提交
149 150
        avaliable_npu_device = re.match(r'npu:\d+', lower_device)
        if not avaliable_gpu_device and not avaliable_xpu_device and not avaliable_npu_device:
151
            raise ValueError(
H
houj04 已提交
152
                "The device must be a string which is like 'cpu', 'gpu', 'gpu:x', 'xpu', 'xpu:x', 'npu' or 'npu:x'"
153
            )
154 155 156
        if avaliable_gpu_device:
            if not core.is_compiled_with_cuda():
                raise ValueError(
157
                    "The device should not be {}, since PaddlePaddle is "
158 159 160 161 162 163 164 165
                    "not compiled with CUDA".format(avaliable_gpu_device))
            device_info_list = device.split(':', 1)
            device_id = device_info_list[1]
            device_id = int(device_id)
            place = core.CUDAPlace(device_id)
        if avaliable_xpu_device:
            if not core.is_compiled_with_xpu():
                raise ValueError(
166
                    "The device should not be {}, since PaddlePaddle is "
167 168 169 170 171
                    "not compiled with XPU".format(avaliable_xpu_device))
            device_info_list = device.split(':', 1)
            device_id = device_info_list[1]
            device_id = int(device_id)
            place = core.XPUPlace(device_id)
H
houj04 已提交
172 173 174 175 176 177 178 179 180
        if avaliable_npu_device:
            if not core.is_compiled_with_npu():
                raise ValueError(
                    "The device should not be {}, since PaddlePaddle is "
                    "not compiled with NPU".format(avaliable_npu_device))
            device_info_list = device.split(':', 1)
            device_id = device_info_list[1]
            device_id = int(device_id)
            place = core.NPUPlace(device_id)
C
chentianyu03 已提交
181
    return place
182

C
chentianyu03 已提交
183 184 185

def set_device(device):
    """
H
houj04 已提交
186
    Paddle supports running calculations on various types of devices, including CPU, GPU, XPU and NPU.
C
chentianyu03 已提交
187 188 189 190 191
    They are represented by string identifiers. This function can specify the global device
    which the OP will run.

    Parameters:
        device(str): This parameter determines the specific running device.
H
houj04 已提交
192 193
            It can be ``cpu``, ``gpu``, ``xpu``, ``npu``, ``gpu:x``, ``xpu:x`` and ``npu:x``,
            where ``x`` is the index of the GPUs, XPUs or NPUs.
C
chentianyu03 已提交
194 195 196 197 198 199 200

    Examples:

     .. code-block:: python
            
        import paddle

201
        paddle.device.set_device("cpu")
C
chentianyu03 已提交
202 203 204 205 206
        x1 = paddle.ones(name='x1', shape=[1, 2], dtype='int32')
        x2 = paddle.zeros(name='x2', shape=[1, 2], dtype='int32')
        data = paddle.stack([x1,x2], axis=1)
    """
    place = _convert_to_place(device)
207 208
    framework._set_expected_place(place)
    return place
209 210 211 212 213


def get_device():
    """
    This funciton can get the current global device of the program is running.
H
houj04 已提交
214
    It's a string which is like 'cpu', 'gpu:x', 'xpu:x' and 'npu:x'. if the global device is not
215
    set, it will return a string which is 'gpu:x' when cuda is avaliable or it 
216 217 218 219 220 221 222
    will return a string which is 'cpu' when cuda is not avaliable.

    Examples:

     .. code-block:: python
            
        import paddle
223
        device = paddle.device.get_device()
224 225 226 227 228 229 230 231 232

    """
    device = ''
    place = framework._current_expected_place()
    if isinstance(place, core.CPUPlace):
        device = 'cpu'
    elif isinstance(place, core.CUDAPlace):
        device_id = place.get_device_id()
        device = 'gpu:' + str(device_id)
233 234 235
    elif isinstance(place, core.XPUPlace):
        device_id = place.get_device_id()
        device = 'xpu:' + str(device_id)
H
houj04 已提交
236 237 238
    elif isinstance(place, core.NPUPlace):
        device_id = place.get_device_id()
        device = 'npu:' + str(device_id)
239 240

    return device