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.5 kB

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