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

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

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