device.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. # Copyright (c) 2024 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import os
  15. import GPUtil
  16. import lazy_paddle as paddle
  17. from . import logging
  18. from .custom_device_whitelist import (
  19. DCU_WHITELIST,
  20. GCU_WHITELIST,
  21. MLU_WHITELIST,
  22. NPU_WHITELIST,
  23. XPU_WHITELIST,
  24. )
  25. from .flags import DISABLE_DEV_MODEL_WL
  26. SUPPORTED_DEVICE_TYPE = ["cpu", "gpu", "xpu", "npu", "mlu", "gcu", "dcu"]
  27. def constr_device(device_type, device_ids):
  28. if device_type == "cpu" and device_ids is not None:
  29. raise ValueError("`device_ids` must be None for CPUs")
  30. if device_ids:
  31. device_ids = ",".join(map(str, device_ids))
  32. return f"{device_type}:{device_ids}"
  33. else:
  34. return f"{device_type}"
  35. def get_default_device():
  36. avail_gpus = GPUtil.getAvailable()
  37. if not avail_gpus:
  38. # maybe edge devices like Jetson
  39. if os.path.exists("/etc/nv_tegra_release"):
  40. avail_gpus = [0]
  41. logging.info(
  42. "Detected that the current device is a Jetson edge device. The default behavior will be to use GPU: 0"
  43. )
  44. if not avail_gpus:
  45. return "cpu"
  46. else:
  47. return constr_device("gpu", [avail_gpus[0]])
  48. def parse_device(device):
  49. """parse_device"""
  50. # According to https://www.paddlepaddle.org.cn/documentation/docs/zh/api/paddle/device/set_device_cn.html
  51. parts = device.split(":")
  52. if len(parts) > 2:
  53. raise ValueError(f"Invalid device: {device}")
  54. if len(parts) == 1:
  55. device_type, device_ids = parts[0], None
  56. else:
  57. device_type, device_ids = parts
  58. device_ids = device_ids.split(",")
  59. for device_id in device_ids:
  60. if not device_id.isdigit():
  61. raise ValueError(
  62. f"Device ID must be an integer. Invalid device ID: {device_id}"
  63. )
  64. device_ids = list(map(int, device_ids))
  65. device_type = device_type.lower()
  66. # raise_unsupported_device_error(device_type, SUPPORTED_DEVICE_TYPE)
  67. assert device_type.lower() in SUPPORTED_DEVICE_TYPE
  68. if device_type == "cpu" and device_ids is not None:
  69. raise ValueError("No Device ID should be specified for CPUs")
  70. return device_type, device_ids
  71. def update_device_num(device, num):
  72. device_type, device_ids = parse_device(device)
  73. if device_ids:
  74. assert len(device_ids) >= num
  75. return constr_device(device_type, device_ids[:num])
  76. else:
  77. return constr_device(device_type, device_ids)
  78. def set_env_for_device(device):
  79. device_type, _ = parse_device(device)
  80. return set_env_for_device_type(device_type)
  81. def set_env_for_device_type(device_type):
  82. def _set(envs):
  83. for key, val in envs.items():
  84. os.environ[key] = val
  85. logging.debug(f"{key} has been set to {val}.")
  86. # XXX: is_compiled_with_rocm() must be True on dcu platform ?
  87. if device_type.lower() == "dcu" and paddle.is_compiled_with_rocm():
  88. envs = {"FLAGS_conv_workspace_size_limit": "2000"}
  89. _set(envs)
  90. if device_type.lower() == "npu":
  91. envs = {
  92. "FLAGS_npu_jit_compile": "0",
  93. "FLAGS_use_stride_kernel": "0",
  94. "FLAGS_allocator_strategy": "auto_growth",
  95. "CUSTOM_DEVICE_BLACK_LIST": "pad3d,pad3d_grad,set_value,set_value_with_tensor",
  96. "FLAGS_npu_scale_aclnn": "True",
  97. "FLAGS_npu_split_aclnn": "True",
  98. }
  99. _set(envs)
  100. if device_type.lower() == "xpu":
  101. envs = {
  102. "BKCL_FORCE_SYNC": "1",
  103. "BKCL_TIMEOUT": "1800",
  104. "FLAGS_use_stride_kernel": "0",
  105. "XPU_BLACK_LIST": "pad3d",
  106. }
  107. _set(envs)
  108. if device_type.lower() == "mlu":
  109. envs = {"FLAGS_use_stride_kernel": "0"}
  110. _set(envs)
  111. if device_type.lower() == "gcu":
  112. envs = {"FLAGS_use_stride_kernel": "0"}
  113. _set(envs)
  114. def check_supported_device_type(device_type, model_name):
  115. if DISABLE_DEV_MODEL_WL:
  116. logging.warning(
  117. "Skip checking if model is supported on device because the flag `PADDLE_PDX_DISABLE_DEV_MODEL_WL` has been set."
  118. )
  119. return
  120. if device_type == "dcu":
  121. assert (
  122. model_name in DCU_WHITELIST
  123. ), f"The DCU device does not yet support `{model_name}` model!"
  124. elif device_type == "mlu":
  125. assert (
  126. model_name in MLU_WHITELIST
  127. ), f"The MLU device does not yet support `{model_name}` model!"
  128. elif device_type == "npu":
  129. assert (
  130. model_name in NPU_WHITELIST
  131. ), f"The NPU device does not yet support `{model_name}` model!"
  132. elif device_type == "xpu":
  133. assert (
  134. model_name in XPU_WHITELIST
  135. ), f"The XPU device does not yet support `{model_name}` model!"
  136. elif device_type == "gcu":
  137. assert (
  138. model_name in GCU_WHITELIST
  139. ), f"The GCU device does not yet support `{model_name}` model!"
  140. def check_supported_device(device, model_name):
  141. device_type, _ = parse_device(device)
  142. return check_supported_device_type(device_type, model_name)