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

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

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