You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

device.py 5.5 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
  5. #
  6. # Unless required by applicable law or agreed to in writing,
  7. # software distributed under the License is distributed on an
  8. # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. import os
  10. import re
  11. from typing import Optional
  12. from .core._imperative_rt.common import CompNode, DeviceType
  13. from .core._imperative_rt.common import (
  14. get_cuda_compute_capability as _get_cuda_compute_capability,
  15. )
  16. from .core._imperative_rt.common import set_prealloc_config as _set_prealloc_config
  17. from .core._imperative_rt.common import what_is_xpu as _what_is_xpu
  18. __all__ = [
  19. "is_cuda_available",
  20. "get_device_count",
  21. "get_default_device",
  22. "set_default_device",
  23. "get_mem_status_bytes",
  24. "get_cuda_compute_capability",
  25. "set_prealloc_config",
  26. "DeviceType",
  27. ]
  28. def _valid_device(inp):
  29. if isinstance(inp, str) and re.match("^([cxg]pu|rocm)(\d+|\d+:\d+|x)$", inp):
  30. return True
  31. return False
  32. def _str2device_type(type_str: str, allow_unspec: bool = True):
  33. type_str = type_str.upper()
  34. if type_str == "CPU":
  35. return DeviceType.CPU
  36. elif type_str == "GPU" or type_str == "CUDA":
  37. return DeviceType.CUDA
  38. elif type_str == "CAMBRICON":
  39. return DeviceType.CAMBRICON
  40. elif type_str == "ATLAS":
  41. return DeviceType.ATLAS
  42. elif type_str == "ROCM" or type_str == "AMDGPU":
  43. return DeviceType.ROCM
  44. else:
  45. assert (
  46. allow_unspec and type_str == "XPU"
  47. ), "device type can only be cpu, gpu or xpu"
  48. return DeviceType.UNSPEC
  49. _device_type_set = {"cpu", "gpu", "xpu", "rocm"}
  50. def get_device_count(device_type: str) -> int:
  51. r"""Gets number of devices installed on this system.
  52. Args:
  53. device_type: device type, one of 'gpu' or 'cpu'
  54. """
  55. assert device_type in _device_type_set, "device must be one of {}".format(
  56. _device_type_set
  57. )
  58. device_type = _str2device_type(device_type)
  59. return CompNode._get_device_count(device_type, False)
  60. def is_cuda_available() -> bool:
  61. r"""Returns whether cuda device is available on this system."""
  62. t = _str2device_type("gpu")
  63. return CompNode._get_device_count(t, False) > 0
  64. def is_cambricon_available() -> bool:
  65. r"""Returns whether cambricon device is available on this system."""
  66. t = _str2device_type("cambricon")
  67. return CompNode._get_device_count(t, False) > 0
  68. def is_atlas_available() -> bool:
  69. r"""Returns whether atlas device is available on this system."""
  70. t = _str2device_type("atlas")
  71. return CompNode._get_device_count(t, False) > 0
  72. def is_rocm_available() -> bool:
  73. r"""Returns whether rocm device is available on this system."""
  74. t = _str2device_type("rocm")
  75. return CompNode._get_device_count(t, False) > 0
  76. def set_default_device(device: str = "xpux"):
  77. r"""Sets default computing node.
  78. Args:
  79. device: default device type.
  80. Note:
  81. * The type can be 'cpu0', 'cpu1', etc., or 'gpu0', 'gpu1', etc.,
  82. to specify the particular CPU or GPU to use.
  83. * 'cpux' and 'gpux' can also be used to specify any number of CPU or GPU devices.
  84. * The default value is 'xpux' to specify any device available.
  85. * The priority of using GPU is higher when both GPU and CPU are available.
  86. * 'multithread' device type is avaliable when inference,
  87. which implements multi-threading parallelism at the operator level.
  88. For example, 'multithread4' will compute with 4 threads.
  89. * It can also be set by environment variable ``MGE_DEFAULT_DEVICE``.
  90. """
  91. assert _valid_device(device), "Invalid device name {}".format(device)
  92. CompNode._set_default_device(device)
  93. def get_default_device() -> str:
  94. r"""Gets default computing node.
  95. It returns the value set by :func:`~.set_default_device`.
  96. """
  97. return CompNode._get_default_device()
  98. def get_mem_status_bytes(device: Optional[str] = None):
  99. r"""Get total and free memory on the computing device in bytes."""
  100. if device is None:
  101. device = get_default_device()
  102. tot, free = CompNode(device).get_mem_status_bytes
  103. return tot, free
  104. def get_cuda_compute_capability(device: int, device_type=DeviceType.CUDA) -> int:
  105. r"""
  106. Get compute capability of the specified device.
  107. It returns a version number, or `SM version`.
  108. """
  109. return _get_cuda_compute_capability(device, device_type)
  110. set_default_device(os.getenv("MGE_DEFAULT_DEVICE", "xpux"))
  111. def set_prealloc_config(
  112. alignment: int = 1,
  113. min_req: int = 32 * 1024 * 1024,
  114. max_overhead: int = 0,
  115. growth_factor=2.0,
  116. device_type=DeviceType.CUDA,
  117. ):
  118. r"""Specifies how to pre-allocate from raw device allocator.
  119. Args:
  120. alignment: specifies the alignment in bytes.
  121. min_req: min request size in bytes.
  122. max_overhead: max overhead above required size in bytes.
  123. growth_factor: request size / cur allocated`
  124. device_type: the device type
  125. alignment: int:
  126. min_req: int:
  127. max_overhead: int:
  128. """
  129. assert alignment > 0
  130. assert min_req > 0
  131. assert max_overhead >= 0
  132. assert growth_factor >= 1
  133. _set_prealloc_config(alignment, min_req, max_overhead, growth_factor, device_type)
  134. def what_is_xpu():
  135. return _what_is_xpu().name.lower()

MegEngine 安装包中集成了使用 GPU 运行代码所需的 CUDA 环境,不用区分 CPU 和 GPU 版。 如果想要运行 GPU 程序,请确保机器本身配有 GPU 硬件设备并安装好驱动。 如果你想体验在云端 GPU 算力平台进行深度学习开发的感觉,欢迎访问 MegStudio 平台