__init__.py 9.1 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',
J
jianghaicheng 已提交
31
    'IPUPlace',
W
Wenyu 已提交
32
    'is_compiled_with_xpu',
J
jianghaicheng 已提交
33
    'is_compiled_with_ipu',
34
    'is_compiled_with_cinn',
35
    'is_compiled_with_cuda',
36
    'is_compiled_with_rocm',
37
    'is_compiled_with_npu'
38 39
]

40 41 42
_cudnn_version = None


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

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

    Examples:
        .. code-block:: python

            import paddle
55
            support_npu = paddle.device.is_compiled_with_npu()
56 57 58 59
    """
    return core.is_compiled_with_npu()


J
jianghaicheng 已提交
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
def is_compiled_with_ipu():
    """
    Whether paddle was built with WITH_IPU=ON to support Graphcore IPU.

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

    Examples:
        .. code-block:: python

            import paddle
            support_ipu = paddle.is_compiled_with_ipu()
    """
    return core.is_compiled_with_ipu()


def IPUPlace():
    """
    Return a Graphcore IPU Place

    Examples:
        .. code-block:: python

            # required: ipu

            import paddle
            place = paddle.device.IPUPlace()
    """
    return core.IPUPlace()


90 91 92 93 94 95 96 97 98 99
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
100
            support_xpu = paddle.device.is_compiled_with_xpu()
101 102 103 104 105 106 107 108 109 110 111 112 113
    """
    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
114

115 116
            # required: xpu
            
117
            import paddle
118
            place = paddle.device.XPUPlace(0)
119 120 121 122
    """
    return core.XPUPlace(dev_id)


123 124 125 126 127 128 129 130 131 132 133 134 135
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

136
            cudnn_version = paddle.device.get_cudnn_version()
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153



    """
    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

154

C
chentianyu03 已提交
155
def _convert_to_place(device):
156 157 158
    lower_device = device.lower()
    if lower_device == 'cpu':
        place = core.CPUPlace()
159 160
    elif lower_device == 'gpu':
        if not core.is_compiled_with_cuda():
161 162
            raise ValueError("The device should not be 'gpu', "
                             "since PaddlePaddle is not compiled with CUDA")
163
        place = core.CUDAPlace(ParallelEnv().dev_id)
164 165
    elif lower_device == 'xpu':
        if not core.is_compiled_with_xpu():
166 167
            raise ValueError("The device should not be 'xpu', "
                             "since PaddlePaddle is not compiled with XPU")
T
taixiurong 已提交
168 169 170
        selected_xpus = os.getenv("FLAGS_selected_xpus", "0").split(",")
        device_id = int(selected_xpus[0])
        place = core.XPUPlace(device_id)
H
houj04 已提交
171 172 173 174 175 176 177
    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)
J
jianghaicheng 已提交
178 179 180 181 182 183
    elif lower_device == 'ipu':
        if not core.is_compiled_with_ipu():
            raise ValueError(
                "The device should not be 'ipu', " \
                "since PaddlePaddle is not compiled with IPU")
        place = core.IPUPlace()
184
    else:
185 186
        avaliable_gpu_device = re.match(r'gpu:\d+', lower_device)
        avaliable_xpu_device = re.match(r'xpu:\d+', lower_device)
H
houj04 已提交
187 188
        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:
189
            raise ValueError(
J
jianghaicheng 已提交
190
                "The device must be a string which is like 'cpu', 'gpu', 'gpu:x', 'xpu', 'xpu:x', 'npu', 'npu:x' or ipu"
191
            )
192 193 194
        if avaliable_gpu_device:
            if not core.is_compiled_with_cuda():
                raise ValueError(
195
                    "The device should not be {}, since PaddlePaddle is "
196 197 198 199 200 201 202 203
                    "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(
204
                    "The device should not be {}, since PaddlePaddle is "
205 206 207 208 209
                    "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 已提交
210 211 212 213 214 215 216 217 218
        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 已提交
219
    return place
220

C
chentianyu03 已提交
221 222 223

def set_device(device):
    """
J
jianghaicheng 已提交
224
    Paddle supports running calculations on various types of devices, including CPU, GPU, XPU, NPU and IPU.
C
chentianyu03 已提交
225 226 227 228 229
    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.
J
jianghaicheng 已提交
230
            It can be ``cpu``, ``gpu``, ``xpu``, ``npu``, ``gpu:x``, ``xpu:x``, ``npu:x`` and ``ipu``,
H
houj04 已提交
231
            where ``x`` is the index of the GPUs, XPUs or NPUs.
C
chentianyu03 已提交
232 233 234 235 236 237 238

    Examples:

     .. code-block:: python
            
        import paddle

239
        paddle.device.set_device("cpu")
C
chentianyu03 已提交
240 241 242 243 244
        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)
245 246
    framework._set_expected_place(place)
    return place
247 248 249 250 251


def get_device():
    """
    This funciton can get the current global device of the program is running.
H
houj04 已提交
252
    It's a string which is like 'cpu', 'gpu:x', 'xpu:x' and 'npu:x'. if the global device is not
253
    set, it will return a string which is 'gpu:x' when cuda is avaliable or it 
254 255 256 257 258 259 260
    will return a string which is 'cpu' when cuda is not avaliable.

    Examples:

     .. code-block:: python
            
        import paddle
261
        device = paddle.device.get_device()
262 263 264 265 266 267 268 269 270

    """
    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)
271 272 273
    elif isinstance(place, core.XPUPlace):
        device_id = place.get_device_id()
        device = 'xpu:' + str(device_id)
H
houj04 已提交
274 275 276
    elif isinstance(place, core.NPUPlace):
        device_id = place.get_device_id()
        device = 'npu:' + str(device_id)
J
jianghaicheng 已提交
277 278 279 280 281
    elif isinstance(place, core.IPUPlace):
        num_devices = core.get_ipu_device_count()
        device = "ipus:{{0-{}}}".format(num_devices - 1)
    else:
        raise ValueError("The device specification {} is invalid".format(place))
282 283

    return device