__init__.py 17.6 KB
Newer Older
1
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
2
#
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
import paddle
16
from paddle.fluid import core
17
from paddle.fluid.wrapped_decorator import signature_safe_contextmanager
18
from paddle.utils import deprecated
19 20 21 22 23 24 25 26 27

from .streams import Stream  # noqa: F401
from .streams import Event  # noqa: F401

__all__ = [
    'Stream',
    'Event',
    'current_stream',
    'synchronize',
L
Linjie Chen 已提交
28
    'device_count',
29
    'empty_cache',
30 31 32 33
    'max_memory_allocated',
    'max_memory_reserved',
    'memory_allocated',
    'memory_reserved',
34
    'stream_guard',
35
    'get_device_properties',
36 37
    'get_device_name',
    'get_device_capability',
38 39 40
]


41 42 43 44 45 46
@deprecated(
    since="2.5.0",
    update_to="paddle.device.current_stream",
    level=1,
    reason="current_stream in paddle.device.cuda will be removed in future",
)
47 48 49 50 51
def current_stream(device=None):
    '''
    Return the current CUDA stream by the device.

    Parameters:
52
        device(paddle.CUDAPlace()|int, optional): The device or the ID of the device which want to get stream from.
53
        If device is None, the device is the current device. Default: None.
54

55 56
    Returns:
        CUDAStream: the stream to the device.
57

58 59 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
    Examples:
        .. code-block:: python

            # required: gpu
            import paddle

            s1 = paddle.device.cuda.current_stream()

            s2 = paddle.device.cuda.current_stream(0)

            s3 = paddle.device.cuda.current_stream(paddle.CUDAPlace(0))

    '''

    device_id = -1

    if device is not None:
        if isinstance(device, int):
            device_id = device
        elif isinstance(device, core.CUDAPlace):
            device_id = device.get_device_id()
        else:
            raise ValueError("device type must be int or paddle.CUDAPlace")

    return core._get_current_stream(device_id)


85 86 87 88 89 90
@deprecated(
    since="2.5.0",
    update_to="paddle.device.synchronize",
    level=1,
    reason="synchronize in paddle.device.cuda will be removed in future",
)
91 92 93 94 95 96 97
def synchronize(device=None):
    '''
    Wait for the compute on the given CUDA device to finish.

    Parameters:
        device(paddle.CUDAPlace()|int, optional): The device or the ID of the device.
        If device is None, the device is the current device. Default: None.
98

99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
    Examples:
        .. code-block:: python

            # required: gpu
            import paddle

            paddle.device.cuda.synchronize()
            paddle.device.cuda.synchronize(0)
            paddle.device.cuda.synchronize(paddle.CUDAPlace(0))

    '''

    device_id = -1

    if device is not None:
        if isinstance(device, int):
            device_id = device
        elif isinstance(device, core.CUDAPlace):
            device_id = device.get_device_id()
        else:
            raise ValueError("device type must be int or paddle.CUDAPlace")

    return core._device_synchronize(device_id)
L
Linjie Chen 已提交
122 123 124 125 126


def device_count():
    '''
    Return the number of GPUs available.
127

L
Linjie Chen 已提交
128 129 130 131 132 133 134 135 136 137 138 139
    Returns:
        int: the number of GPUs available.

    Examples:
        .. code-block:: python

            import paddle

            paddle.device.cuda.device_count()

    '''

140 141 142 143 144
    num_gpus = (
        core.get_cuda_device_count()
        if hasattr(core, 'get_cuda_device_count')
        else 0
    )
L
Linjie Chen 已提交
145 146

    return num_gpus
147 148 149


def empty_cache():
150
    '''
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
    Releases idle cached memory held by the allocator so that those can be used in other GPU
    application and visible in `nvidia-smi`. In most cases you don't need to use this function,
    Paddle does not release the memory back to the OS when you remove Tensors on the GPU,
    Because it keeps gpu memory in a pool so that next allocations can be done much faster.

    Examples:
        .. code-block:: python

            import paddle

            # required: gpu
            paddle.set_device("gpu")
            tensor = paddle.randn([512, 512, 512], "float")
            del tensor
            paddle.device.cuda.empty_cache()
166
    '''
167 168 169

    if core.is_compiled_with_cuda():
        core.cuda_empty_cache()
170 171


172 173 174 175 176
def extract_cuda_device_id(device, op_name):
    '''
    Return the id of the given cuda device. It is just a utility that will not be exposed to users.

    Args:
177
        device(paddle.CUDAPlace or int or str): The device, the id of the device or
178 179 180 181 182 183
            the string name of device like 'gpu:x'.
            Default: None.

    Return:
        int: The id of the given device. If device is None, return the id of current device.
    '''
184
    if device is None:
185 186 187 188 189 190 191 192 193 194 195 196
        return core.get_cuda_current_device_id()

    if isinstance(device, int):
        device_id = device
    elif isinstance(device, core.CUDAPlace):
        device_id = device.get_device_id()
    elif isinstance(device, str):
        if device.startswith('gpu:'):
            device_id = int(device[4:])
        else:
            raise ValueError(
                "The current string {} is not expected. Because {} only support string which is like 'gpu:x'. "
197 198
                "Please input appropriate string again!".format(device, op_name)
            )
199 200 201
    else:
        raise ValueError(
            "The device type {} is not expected. Because {} only support int, str or paddle.CUDAPlace. "
202 203
            "Please input appropriate device again!".format(device, op_name)
        )
204

205 206 207 208 209
    assert (
        device_id >= 0
    ), f"The device id must be not less than 0, but got id = {device_id}."
    assert (
        device_id < device_count()
210 211 212 213 214 215 216 217 218
    ), f"The device id {device_id} exceeds gpu card number {device_count()}"

    return device_id


def max_memory_allocated(device=None):
    '''
    Return the peak size of gpu memory that is allocated to tensor of the given device.

219
    Note:
220
        The size of GPU memory allocated to tensor is 256-byte aligned in Paddle, which may larger than the memory size that tensor actually need.
221 222 223
        For instance, a float32 tensor with shape [1] in GPU will take up 256 bytes memory, even though storing a float32 data requires only 4 bytes.

    Args:
224
        device(paddle.CUDAPlace or int or str, optional): The device, the id of the device or
225
            the string name of device like 'gpu:x'. If device is None, the device is the current device.
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
            Default: None.

    Return:
        int: The peak size of gpu memory that is allocated to tensor of the given device, in bytes.

    Examples:
        .. code-block:: python

            # required: gpu
            import paddle

            max_memory_allocated_size = paddle.device.cuda.max_memory_allocated(paddle.CUDAPlace(0))
            max_memory_allocated_size = paddle.device.cuda.max_memory_allocated(0)
            max_memory_allocated_size = paddle.device.cuda.max_memory_allocated("gpu:0")
    '''
    name = "paddle.device.cuda.max_memory_allocated"
    if not core.is_compiled_with_cuda():
        raise ValueError(
            f"The API {name} is not supported in CPU-only PaddlePaddle. Please reinstall PaddlePaddle with GPU support to call this API."
        )
    device_id = extract_cuda_device_id(device, op_name=name)
247
    return core.device_memory_stat_peak_value("Allocated", device_id)
248 249 250 251 252 253 254


def max_memory_reserved(device=None):
    '''
    Return the peak size of GPU memory that is held by the allocator of the given device.

    Args:
255
        device(paddle.CUDAPlace or int or str, optional): The device, the id of the device or
256
            the string name of device like 'gpu:x'. If device is None, the device is the current device.
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
            Default: None.

    Return:
        int: The peak size of GPU memory that is held by the allocator of the given device, in bytes.

    Examples:
        .. code-block:: python

            # required: gpu
            import paddle

            max_memory_reserved_size = paddle.device.cuda.max_memory_reserved(paddle.CUDAPlace(0))
            max_memory_reserved_size = paddle.device.cuda.max_memory_reserved(0)
            max_memory_reserved_size = paddle.device.cuda.max_memory_reserved("gpu:0")
    '''
    name = "paddle.device.cuda.max_memory_reserved"
    if not core.is_compiled_with_cuda():
        raise ValueError(
            f"The API {name} is not supported in CPU-only PaddlePaddle. Please reinstall PaddlePaddle with GPU support to call this API."
        )
    device_id = extract_cuda_device_id(device, op_name=name)
278
    return core.device_memory_stat_peak_value("Reserved", device_id)
279 280 281 282 283 284


def memory_allocated(device=None):
    '''
    Return the current size of gpu memory that is allocated to tensor of the given device.

285
    Note:
286 287
        The size of GPU memory allocated to tensor is 256-byte aligned in Paddle, which may be larger than the memory size that tensor actually need.
        For instance, a float32 tensor with shape [1] in GPU will take up 256 bytes memory, even though storing a float32 data requires only 4 bytes.
288 289

    Args:
290 291
        device(paddle.CUDAPlace or int or str): The device, the id of the device or
            the string name of device like 'gpu:x'. If device is None, the device is the current device.
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
            Default: None.

    Return:
        int: The current size of gpu memory that is allocated to tensor of the given device, in bytes.

    Examples:
        .. code-block:: python

            # required: gpu
            import paddle

            memory_allocated_size = paddle.device.cuda.memory_allocated(paddle.CUDAPlace(0))
            memory_allocated_size = paddle.device.cuda.memory_allocated(0)
            memory_allocated_size = paddle.device.cuda.memory_allocated("gpu:0")
    '''
    name = "paddle.device.cuda.memory_allocated"
    if not core.is_compiled_with_cuda():
        raise ValueError(
            f"The API {name} is not supported in CPU-only PaddlePaddle. Please reinstall PaddlePaddle with GPU support to call this API."
        )
    device_id = extract_cuda_device_id(device, op_name=name)
313
    return core.device_memory_stat_current_value("Allocated", device_id)
314 315 316 317 318 319 320


def memory_reserved(device=None):
    '''
    Return the current size of GPU memory that is held by the allocator of the given device.

    Args:
321 322
        device(paddle.CUDAPlace or int or str): The device, the id of the device or
            the string name of device like 'gpu:x'. If device is None, the device is the current device.
323 324 325 326 327
            Default: None.

    Return:
        int: The current size of GPU memory that is held by the allocator of the given device, in bytes.

328
    Examples:
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
        .. code-block:: python

            # required: gpu
            import paddle

            memory_reserved_size = paddle.device.cuda.memory_reserved(paddle.CUDAPlace(0))
            memory_reserved_size = paddle.device.cuda.memory_reserved(0)
            memory_reserved_size = paddle.device.cuda.memory_reserved("gpu:0")
    '''
    name = "paddle.device.cuda.memory_reserved"
    if not core.is_compiled_with_cuda():
        raise ValueError(
            f"The API {name} is not supported in CPU-only PaddlePaddle. Please reinstall PaddlePaddle with GPU support to call this API."
        )
    device_id = extract_cuda_device_id(device, op_name=name)
344
    return core.device_memory_stat_current_value("Reserved", device_id)
345 346


347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
def _set_current_stream(stream):
    '''
    Set the current stream.

    Parameters:
        stream(paddle.device.cuda.Stream): The selected stream.

    Returns:
        CUDAStream: The previous stream.

    '''

    if not isinstance(stream, paddle.device.cuda.Stream):
        raise TypeError("stream type should be paddle.device.cuda.Stream")

    cur_stream = current_stream()
    if id(stream) == id(cur_stream):
        return stream
    return core._set_current_stream(stream)


368 369 370 371 372 373
@deprecated(
    since="2.5.0",
    update_to="paddle.device.stream_guard",
    level=1,
    reason="stream_guard in paddle.device.cuda will be removed in future",
)
374 375 376
@signature_safe_contextmanager
def stream_guard(stream):
    '''
Z
Zman 已提交
377 378
    Notes:
        This API only supports dynamic graph mode currently.
379 380 381 382

    A context manager that specifies the current stream context by the given stream.

    Parameters:
S
Siming Dai 已提交
383
        stream(paddle.device.cuda.Stream): the selected stream. If stream is None, just yield.
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410

    Examples:
        .. code-block:: python

            # required: gpu
            import paddle

            s = paddle.device.cuda.Stream()
            data1 = paddle.ones(shape=[20])
            data2 = paddle.ones(shape=[20])
            with paddle.device.cuda.stream_guard(s):
                data3 = data1 + data2

    '''

    if stream is not None and not isinstance(stream, paddle.device.cuda.Stream):
        raise TypeError("stream type should be paddle.device.cuda.Stream")

    cur_stream = current_stream()
    if stream is None or id(stream) == id(cur_stream):
        yield
    else:
        pre_stream = _set_current_stream(stream)
        try:
            yield
        finally:
            stream = _set_current_stream(pre_stream)
411 412 413 414 415 416 417


def get_device_properties(device=None):
    '''
    Return the properties of given device.

    Args:
418
        device(paddle.CUDAPlace or int or str, optional): The device, the id of the device or
419 420
            the string name of device like 'gpu:x' which to get the properties of the
            device from. If device is None, the device is the current device.
421 422 423
            Default: None.

    Returns:
424 425
        _gpuDeviceProperties: The properties of the device which include ASCII string
        identifying device, major compute capability, minor compute capability, global
426
        memory available and the number of multiprocessors on the device.
427 428

    Examples:
429

430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
        .. code-block:: python

            # required: gpu

            import paddle
            paddle.device.cuda.get_device_properties()
            # _gpuDeviceProperties(name='A100-SXM4-40GB', major=8, minor=0, total_memory=40536MB, multi_processor_count=108)

            paddle.device.cuda.get_device_properties(0)
            # _gpuDeviceProperties(name='A100-SXM4-40GB', major=8, minor=0, total_memory=40536MB, multi_processor_count=108)

            paddle.device.cuda.get_device_properties('gpu:0')
            # _gpuDeviceProperties(name='A100-SXM4-40GB', major=8, minor=0, total_memory=40536MB, multi_processor_count=108)

            paddle.device.cuda.get_device_properties(paddle.CUDAPlace(0))
            # _gpuDeviceProperties(name='A100-SXM4-40GB', major=8, minor=0, total_memory=40536MB, multi_processor_count=108)

    '''

    if not core.is_compiled_with_cuda():
        raise ValueError(
            "The API paddle.device.cuda.get_device_properties is not supported in "
            "CPU-only PaddlePaddle. Please reinstall PaddlePaddle with GPU support "
453 454
            "to call this API."
        )
455 456 457 458 459 460 461 462 463 464 465 466 467

    if device is not None:
        if isinstance(device, int):
            device_id = device
        elif isinstance(device, core.CUDAPlace):
            device_id = device.get_device_id()
        elif isinstance(device, str):
            if device.startswith('gpu:'):
                device_id = int(device[4:])
            else:
                raise ValueError(
                    "The current string {} is not expected. Because paddle.device."
                    "cuda.get_device_properties only support string which is like 'gpu:x'. "
468 469
                    "Please input appropriate string again!".format(device)
                )
470 471 472 473
        else:
            raise ValueError(
                "The device type {} is not expected. Because paddle.device.cuda."
                "get_device_properties only support int, str or paddle.CUDAPlace. "
474 475
                "Please input appropriate device again!".format(device)
            )
476 477 478 479
    else:
        device_id = -1

    return core.get_device_properties(device_id)
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515


def get_device_name(device=None):
    '''
    Return the name of the device which is got from CUDA function `cudaDeviceProp <https://docs.nvidia.com/cuda/cuda-runtime-api/group__CUDART__DEVICE.html#group__CUDART__DEVICE_1g1bf9d625a931d657e08db2b4391170f0>`_.

    Parameters:
        device(paddle.CUDAPlace|int, optional): The device or the ID of the device. If device is None (default), the device is the current device.

    Returns:
        str: The name of the device.

    Examples:

        .. code-block:: python

            # required: gpu

            import paddle

            paddle.device.cuda.get_device_name()

            paddle.device.cuda.get_device_name(0)

            paddle.device.cuda.get_device_name(paddle.CUDAPlace(0))

    '''

    return get_device_properties(device).name


def get_device_capability(device=None):
    '''
    Return the major and minor revision numbers defining the device's compute capability which are got from CUDA function `cudaDeviceProp <https://docs.nvidia.com/cuda/cuda-runtime-api/group__CUDART__DEVICE.html#group__CUDART__DEVICE_1g1bf9d625a931d657e08db2b4391170f0>`_.

    Parameters:
516
        device(paddle.CUDAPlace|int, optional): The device or the ID of the device. If device is None (default), the device is the current device.
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537

    Returns:
        tuple(int,int): the major and minor revision numbers defining the device's compute capability.

    Examples:

        .. code-block:: python

            # required: gpu

            import paddle

            paddle.device.cuda.get_device_capability()

            paddle.device.cuda.get_device_capability(0)

            paddle.device.cuda.get_device_capability(paddle.CUDAPlace(0))

    '''
    prop = get_device_properties(device)
    return prop.major, prop.minor