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 9.7 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. # -*- coding: utf-8 -*-
  2. import os
  3. import re
  4. from typing import Optional
  5. from .core._imperative_rt.common import CompNode, DeviceType
  6. from .core._imperative_rt.common import get_cuda_version as _get_cuda_version
  7. from .core._imperative_rt.common import get_cudnn_version as _get_cudnn_version
  8. from .core._imperative_rt.common import get_device_prop as _get_device_prop
  9. from .core._imperative_rt.common import get_tensorrt_version as _get_tensorrt_version
  10. from .core._imperative_rt.common import set_prealloc_config as _set_prealloc_config
  11. from .core._imperative_rt.common import what_is_xpu as _what_is_xpu
  12. from .core._imperative_rt.utils import _try_coalesce_all_free_memory
  13. __all__ = [
  14. "is_cuda_available",
  15. "is_cambricon_available",
  16. "is_atlas_available",
  17. "is_rocm_available",
  18. "get_device_count",
  19. "get_default_device",
  20. "set_default_device",
  21. "get_mem_status_bytes",
  22. "get_cuda_compute_capability",
  23. "get_cuda_device_property",
  24. "get_cuda_version",
  25. "get_cudnn_version",
  26. "get_tensorrt_version",
  27. "get_allocated_memory",
  28. "get_reserved_memory",
  29. "get_max_reserved_memory",
  30. "get_max_allocated_memory",
  31. "reset_max_memory_stats",
  32. "set_prealloc_config",
  33. "coalesce_free_memory",
  34. ]
  35. class _stream_helper:
  36. def __init__(self):
  37. self.stream = 1
  38. def get_next(self):
  39. out = self.stream
  40. self.stream = self.stream + 1
  41. return out
  42. _sh = _stream_helper()
  43. def _valid_device(inp):
  44. if isinstance(inp, str) and re.match(
  45. "^([cxg]pu|rocm|multithread)(x|\d+)(:\d+)?$", inp
  46. ):
  47. return True
  48. return False
  49. def _str2device_type(type_str: str, allow_unspec: bool = True):
  50. type_str = type_str.upper()
  51. if type_str == "CPU":
  52. return DeviceType.CPU
  53. elif type_str == "GPU" or type_str == "CUDA":
  54. return DeviceType.CUDA
  55. elif type_str == "CAMBRICON":
  56. return DeviceType.CAMBRICON
  57. elif type_str == "ATLAS":
  58. return DeviceType.ATLAS
  59. elif type_str == "ROCM" or type_str == "AMDGPU":
  60. return DeviceType.ROCM
  61. else:
  62. assert (
  63. allow_unspec and type_str == "XPU"
  64. ), "device type can only be cpu, gpu or xpu"
  65. return DeviceType.UNSPEC
  66. _device_type_set = {"cpu", "gpu", "xpu", "rocm"}
  67. def get_device_count(device_type: str) -> int:
  68. r"""Gets number of devices installed on this system.
  69. Args:
  70. device_type: device type, one of 'gpu' or 'cpu'
  71. """
  72. assert device_type in _device_type_set, "device must be one of {}".format(
  73. _device_type_set
  74. )
  75. device_type = _str2device_type(device_type)
  76. return CompNode._get_device_count(device_type, False)
  77. def is_cuda_available() -> bool:
  78. r"""Returns whether cuda device is available on this system."""
  79. t = _str2device_type("gpu")
  80. return CompNode._get_device_count(t, False) > 0
  81. def is_cambricon_available() -> bool:
  82. r"""Returns whether cambricon device is available on this system."""
  83. t = _str2device_type("cambricon")
  84. return CompNode._get_device_count(t, False) > 0
  85. def is_atlas_available() -> bool:
  86. r"""Returns whether atlas device is available on this system."""
  87. t = _str2device_type("atlas")
  88. return CompNode._get_device_count(t, False) > 0
  89. def is_rocm_available() -> bool:
  90. r"""Returns whether rocm device is available on this system."""
  91. t = _str2device_type("rocm")
  92. return CompNode._get_device_count(t, False) > 0
  93. def set_default_device(device: str = "xpux"):
  94. r"""Sets default computing node.
  95. Args:
  96. device: default device type.
  97. Note:
  98. * The type can be 'cpu0', 'cpu1', etc., or 'gpu0', 'gpu1', etc.,
  99. to specify the particular CPU or GPU to use.
  100. * 'cpux' and 'gpux' can also be used to specify any number of CPU or GPU devices.
  101. * The default value is 'xpux' to specify any device available.
  102. * The priority of using GPU is higher when both GPU and CPU are available.
  103. * 'multithread' device type is avaliable when inference,
  104. which implements multi-threading parallelism at the operator level.
  105. For example, 'multithread4' will compute with 4 threads.
  106. * It can also be set by environment variable ``MGE_DEFAULT_DEVICE``.
  107. """
  108. assert _valid_device(device), "Invalid device name {}".format(device)
  109. CompNode._set_default_device(device)
  110. def get_default_device() -> str:
  111. r"""Gets default computing node.
  112. It returns the value set by :func:`~.set_default_device`.
  113. """
  114. return CompNode._get_default_device()
  115. def get_mem_status_bytes(device: Optional[str] = None):
  116. r"""Get total and free memory on the computing device in bytes."""
  117. if device is None:
  118. device = get_default_device()
  119. tot, free = CompNode(device).get_mem_status_bytes
  120. return tot, free
  121. def get_cuda_compute_capability(device: int, device_type=DeviceType.CUDA) -> int:
  122. r"""Gets compute capability of the specified device.
  123. Args:
  124. device: device number.
  125. Returns:
  126. a version number, or `SM version`.
  127. """
  128. prop = _get_device_prop(device, device_type)
  129. return prop.major * 10 + prop.minor
  130. def get_cuda_device_property(device: int, device_type=DeviceType.CUDA):
  131. return _get_device_prop(device, device_type)
  132. def get_allocated_memory(device: Optional[str] = None):
  133. r"""Returns the current memory occupied by tensors on the computing device in bytes.
  134. Due to the asynchronous execution of MegEngine, please call megengine._full_sync
  135. before calling this function in order to get accurate value.
  136. """
  137. if device is None:
  138. device = get_default_device()
  139. return CompNode(device).get_used_memory
  140. def get_reserved_memory(device: Optional[str] = None):
  141. r"""Returns the current memory managed by the caching allocator on the computing device in bytes.
  142. Due to the asynchronous execution of MegEngine, please call megengine._full_sync
  143. before calling this function in order to get accurate value.
  144. """
  145. if device is None:
  146. device = get_default_device()
  147. return CompNode(device).get_reserved_memory
  148. def get_max_reserved_memory(device: Optional[str] = None):
  149. r"""Returns the maximum memory managed by the caching allocator on the computing device in bytes.
  150. Due to the asynchronous execution of MegEngine, please call megengine._full_sync
  151. before calling this function in order to get accurate value.
  152. """
  153. if device is None:
  154. device = get_default_device()
  155. return CompNode(device).get_max_reserved_memory
  156. def get_max_allocated_memory(device: Optional[str] = None):
  157. r"""Returns the maximum memory occupied by tensors on the computing device in bytes.
  158. Due to the asynchronous execution of MegEngine, please call megengine._full_sync
  159. before calling this function in order to get accurate value.
  160. """
  161. if device is None:
  162. device = get_default_device()
  163. return CompNode(device).get_max_used_memory
  164. def reset_max_memory_stats(device: Optional[str] = None):
  165. r"""Resets the maximum stats on the computing device.
  166. Due to the asynchronous execution of MegEngine, please call megengine._full_sync
  167. before calling this function in order to properly reset memory stats.
  168. """
  169. if device is None:
  170. device = get_default_device()
  171. CompNode.reset_max_memory_stats(device)
  172. set_default_device(os.getenv("MGE_DEFAULT_DEVICE", "xpux"))
  173. def set_prealloc_config(
  174. alignment: int = 1,
  175. min_req: int = 32 * 1024 * 1024,
  176. max_overhead: int = 0,
  177. growth_factor=2.0,
  178. device_type=DeviceType.CUDA,
  179. ):
  180. r"""Specifies how to pre-allocate from raw device allocator.
  181. Args:
  182. alignment: specifies the alignment in bytes.
  183. min_req: min request size in bytes.
  184. max_overhead: max overhead above required size in bytes.
  185. growth_factor: request size / cur allocated`
  186. device_type: the device type
  187. alignment: int:
  188. min_req: int:
  189. max_overhead: int:
  190. """
  191. assert alignment > 0
  192. assert min_req > 0
  193. assert max_overhead >= 0
  194. assert growth_factor >= 1
  195. _set_prealloc_config(alignment, min_req, max_overhead, growth_factor, device_type)
  196. def what_is_xpu():
  197. r"""Return the precise device type like ``cpu``, ``cuda`` and so on."""
  198. return _what_is_xpu().name.lower()
  199. def coalesce_free_memory():
  200. r"""This function will try it best to free all consecutive free chunks back to operating system,
  201. small pieces may not be returned.
  202. because of the async processing of megengine, the effect of this func may not be reflected
  203. immediately. if you want to see the effect immediately, you can call megengine._full_sync after
  204. this func was called
  205. .. note::
  206. * This function will not move any memory in-use;
  207. * This function may do nothing if there are no chunks that can be freed.
  208. """
  209. return _try_coalesce_all_free_memory()
  210. def get_cuda_version():
  211. r"""Gets the CUDA version used when compiling MegEngine.
  212. Returns:
  213. a version number, indicating `CUDA_VERSION_MAJOR * 1000 + CUDA_VERSION_MINOR * 10`.
  214. """
  215. return _get_cuda_version()
  216. def get_cudnn_version():
  217. r"""Get the Cudnn version used when compiling MegEngine.
  218. Returns:
  219. a version number, indicating `CUDNN_MAJOR * 1000 + CUDNN_MINOR * 100 + CUDNN_PATCHLEVEL`.
  220. """
  221. return _get_cudnn_version()
  222. def get_tensorrt_version():
  223. r"""Get the TensorRT version used when compiling MegEngine.
  224. Returns:
  225. a version number, indicating `NV_TENSORRT_MAJOR * 1000 + NV_TENSORRT_MINOR * 100 + NV_TENSORRT_PATCH`.
  226. """
  227. return _get_tensorrt_version()