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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  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. "set_prealloc_config",
  27. "coalesce_free_memory",
  28. "DeviceType",
  29. ]
  30. class _stream_helper:
  31. def __init__(self):
  32. self.stream = 1
  33. def get_next(self):
  34. out = self.stream
  35. self.stream = self.stream + 1
  36. return out
  37. _sh = _stream_helper()
  38. def _valid_device(inp):
  39. if isinstance(inp, str) and re.match("^([cxg]pu|rocm)(\d+|\d+:\d+|x)$", inp):
  40. return True
  41. return False
  42. def _str2device_type(type_str: str, allow_unspec: bool = True):
  43. type_str = type_str.upper()
  44. if type_str == "CPU":
  45. return DeviceType.CPU
  46. elif type_str == "GPU" or type_str == "CUDA":
  47. return DeviceType.CUDA
  48. elif type_str == "CAMBRICON":
  49. return DeviceType.CAMBRICON
  50. elif type_str == "ATLAS":
  51. return DeviceType.ATLAS
  52. elif type_str == "ROCM" or type_str == "AMDGPU":
  53. return DeviceType.ROCM
  54. else:
  55. assert (
  56. allow_unspec and type_str == "XPU"
  57. ), "device type can only be cpu, gpu or xpu"
  58. return DeviceType.UNSPEC
  59. _device_type_set = {"cpu", "gpu", "xpu", "rocm"}
  60. def get_device_count(device_type: str) -> int:
  61. r"""Gets number of devices installed on this system.
  62. Args:
  63. device_type: device type, one of 'gpu' or 'cpu'
  64. """
  65. assert device_type in _device_type_set, "device must be one of {}".format(
  66. _device_type_set
  67. )
  68. device_type = _str2device_type(device_type)
  69. return CompNode._get_device_count(device_type, False)
  70. def is_cuda_available() -> bool:
  71. r"""Returns whether cuda device is available on this system."""
  72. t = _str2device_type("gpu")
  73. return CompNode._get_device_count(t, False) > 0
  74. def is_cambricon_available() -> bool:
  75. r"""Returns whether cambricon device is available on this system."""
  76. t = _str2device_type("cambricon")
  77. return CompNode._get_device_count(t, False) > 0
  78. def is_atlas_available() -> bool:
  79. r"""Returns whether atlas device is available on this system."""
  80. t = _str2device_type("atlas")
  81. return CompNode._get_device_count(t, False) > 0
  82. def is_rocm_available() -> bool:
  83. r"""Returns whether rocm device is available on this system."""
  84. t = _str2device_type("rocm")
  85. return CompNode._get_device_count(t, False) > 0
  86. def set_default_device(device: str = "xpux"):
  87. r"""Sets default computing node.
  88. Args:
  89. device: default device type.
  90. Note:
  91. * The type can be 'cpu0', 'cpu1', etc., or 'gpu0', 'gpu1', etc.,
  92. to specify the particular CPU or GPU to use.
  93. * 'cpux' and 'gpux' can also be used to specify any number of CPU or GPU devices.
  94. * The default value is 'xpux' to specify any device available.
  95. * The priority of using GPU is higher when both GPU and CPU are available.
  96. * 'multithread' device type is avaliable when inference,
  97. which implements multi-threading parallelism at the operator level.
  98. For example, 'multithread4' will compute with 4 threads.
  99. * It can also be set by environment variable ``MGE_DEFAULT_DEVICE``.
  100. """
  101. assert _valid_device(device), "Invalid device name {}".format(device)
  102. CompNode._set_default_device(device)
  103. def get_default_device() -> str:
  104. r"""Gets default computing node.
  105. It returns the value set by :func:`~.set_default_device`.
  106. """
  107. return CompNode._get_default_device()
  108. def get_mem_status_bytes(device: Optional[str] = None):
  109. r"""Get total and free memory on the computing device in bytes."""
  110. if device is None:
  111. device = get_default_device()
  112. tot, free = CompNode(device).get_mem_status_bytes
  113. return tot, free
  114. def get_cuda_compute_capability(device: int, device_type=DeviceType.CUDA) -> int:
  115. r"""Gets compute capability of the specified device.
  116. Args:
  117. device: device number.
  118. Returns:
  119. a version number, or `SM version`.
  120. """
  121. return _get_cuda_compute_capability(device, device_type)
  122. set_default_device(os.getenv("MGE_DEFAULT_DEVICE", "xpux"))
  123. def set_prealloc_config(
  124. alignment: int = 1,
  125. min_req: int = 32 * 1024 * 1024,
  126. max_overhead: int = 0,
  127. growth_factor=2.0,
  128. device_type=DeviceType.CUDA,
  129. ):
  130. r"""Specifies how to pre-allocate from raw device allocator.
  131. Args:
  132. alignment: specifies the alignment in bytes.
  133. min_req: min request size in bytes.
  134. max_overhead: max overhead above required size in bytes.
  135. growth_factor: request size / cur allocated`
  136. device_type: the device type
  137. alignment: int:
  138. min_req: int:
  139. max_overhead: int:
  140. """
  141. assert alignment > 0
  142. assert min_req > 0
  143. assert max_overhead >= 0
  144. assert growth_factor >= 1
  145. _set_prealloc_config(alignment, min_req, max_overhead, growth_factor, device_type)
  146. def what_is_xpu():
  147. return _what_is_xpu().name.lower()
  148. def coalesce_free_memory():
  149. r"""This function will try it best to free all consecutive free chunks back to operating system,
  150. small pieces may not be returned.
  151. because of the async processing of megengine, the effect of this func may not be reflected
  152. immediately. if you want to see the effect immediately, you can call megengine._full_sync after
  153. this func was called
  154. .. note::
  155. Please notice that this function will not move any memory in-use.
  156. Please notice that this function may do nothing if there are no chunks that can be freed
  157. """
  158. return _try_coalesce_all_free_memory()

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