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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  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. from .core._imperative_rt.utils import _try_coalesce_all_free_memory
  19. __all__ = [
  20. "is_cuda_available",
  21. "get_device_count",
  22. "get_default_device",
  23. "set_default_device",
  24. "get_mem_status_bytes",
  25. "get_cuda_compute_capability",
  26. "get_allocated_memory",
  27. "get_reserved_memory",
  28. "get_max_reserved_memory",
  29. "get_max_allocated_memory",
  30. "reset_max_memory_stats",
  31. "set_prealloc_config",
  32. "coalesce_free_memory",
  33. "DeviceType",
  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("^([cxg]pu|rocm)(\d+|\d+:\d+|x)$", inp):
  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. return _get_cuda_compute_capability(device, device_type)
  127. def get_allocated_memory(device: Optional[str] = None):
  128. r"""Returns the current memory occupied by tensors on the computing device in bytes.
  129. Due to the asynchronous execution of MegEngine, please call megengine.sync
  130. before calling this function in order to get accurate value.
  131. """
  132. if device is None:
  133. device = get_default_device()
  134. return CompNode(device).get_used_memory
  135. def get_reserved_memory(device: Optional[str] = None):
  136. r"""Returns the current memory managed by the caching allocator on the computing device in bytes.
  137. Due to the asynchronous execution of MegEngine, please call megengine.sync
  138. before calling this function in order to get accurate value.
  139. """
  140. if device is None:
  141. device = get_default_device()
  142. return CompNode(device).get_reserved_memory
  143. def get_max_reserved_memory(device: Optional[str] = None):
  144. r"""Returns the maximum memory managed by the caching allocator on the computing device in bytes.
  145. Due to the asynchronous execution of MegEngine, please call megengine.sync
  146. before calling this function in order to get accurate value.
  147. """
  148. if device is None:
  149. device = get_default_device()
  150. return CompNode(device).get_max_reserved_memory
  151. def get_max_allocated_memory(device: Optional[str] = None):
  152. r"""Returns the maximum memory occupied by tensors on the computing device in bytes.
  153. Due to the asynchronous execution of MegEngine, please call megengine.sync
  154. before calling this function in order to get accurate value.
  155. """
  156. if device is None:
  157. device = get_default_device()
  158. return CompNode(device).get_max_used_memory
  159. def reset_max_memory_stats(device: Optional[str] = None):
  160. r"""Resets the maximum stats on the computing device.
  161. Due to the asynchronous execution of MegEngine, please call megengine.sync
  162. before calling this function in order to properly reset memory stats.
  163. """
  164. if device is None:
  165. device = get_default_device()
  166. CompNode.reset_max_memory_stats(device)
  167. set_default_device(os.getenv("MGE_DEFAULT_DEVICE", "xpux"))
  168. def set_prealloc_config(
  169. alignment: int = 1,
  170. min_req: int = 32 * 1024 * 1024,
  171. max_overhead: int = 0,
  172. growth_factor=2.0,
  173. device_type=DeviceType.CUDA,
  174. ):
  175. r"""Specifies how to pre-allocate from raw device allocator.
  176. Args:
  177. alignment: specifies the alignment in bytes.
  178. min_req: min request size in bytes.
  179. max_overhead: max overhead above required size in bytes.
  180. growth_factor: request size / cur allocated`
  181. device_type: the device type
  182. alignment: int:
  183. min_req: int:
  184. max_overhead: int:
  185. """
  186. assert alignment > 0
  187. assert min_req > 0
  188. assert max_overhead >= 0
  189. assert growth_factor >= 1
  190. _set_prealloc_config(alignment, min_req, max_overhead, growth_factor, device_type)
  191. def what_is_xpu():
  192. return _what_is_xpu().name.lower()
  193. def coalesce_free_memory():
  194. r"""This function will try it best to free all consecutive free chunks back to operating system,
  195. small pieces may not be returned.
  196. because of the async processing of megengine, the effect of this func may not be reflected
  197. immediately. if you want to see the effect immediately, you can call megengine.sync after
  198. this func was called
  199. .. note::
  200. * This function will not move any memory in-use;
  201. * This function may do nothing if there are no chunks that can be freed.
  202. """
  203. return _try_coalesce_all_free_memory()