device.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. # copyright (c) 2024 PaddlePaddle Authors. All Rights Reserve.
  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 .errors import raise_unsupported_device_error
  19. from .custom_device_whitelist import (
  20. DCU_WHITELIST,
  21. MLU_WHITELIST,
  22. NPU_WHITELIST,
  23. XPU_WHITELIST,
  24. GCU_WHITELIST,
  25. )
  26. SUPPORTED_DEVICE_TYPE = ["cpu", "gpu", "xpu", "npu", "mlu", "gcu", "dcu"]
  27. def _constr_device(device_type, device_ids):
  28. if device_ids:
  29. device_ids = ",".join(map(str, device_ids))
  30. return f"{device_type}:{device_ids}"
  31. else:
  32. return f"{device_type}"
  33. def get_default_device():
  34. avail_gpus = GPUtil.getAvailable()
  35. if not avail_gpus:
  36. # maybe edge devices like Jetson
  37. if os.path.exists("/etc/nv_tegra_release"):
  38. avail_gpus = [0]
  39. logging.info(
  40. "Detected that the current device is a Jetson edge device. The default behavior will be to use GPU: 0"
  41. )
  42. if not avail_gpus:
  43. return "cpu"
  44. else:
  45. return _constr_device("gpu", [avail_gpus[0]])
  46. def parse_device(device):
  47. """parse_device"""
  48. # According to https://www.paddlepaddle.org.cn/documentation/docs/zh/api/paddle/device/set_device_cn.html
  49. parts = device.split(":")
  50. if len(parts) > 2:
  51. raise ValueError(f"Invalid device: {device}")
  52. if len(parts) == 1:
  53. device_type, device_ids = parts[0], None
  54. else:
  55. device_type, device_ids = parts
  56. device_ids = device_ids.split(",")
  57. for device_id in device_ids:
  58. if not device_id.isdigit():
  59. raise ValueError(
  60. f"Device ID must be an integer. Invalid device ID: {device_id}"
  61. )
  62. device_ids = list(map(int, device_ids))
  63. device_type = device_type.lower()
  64. # raise_unsupported_device_error(device_type, SUPPORTED_DEVICE_TYPE)
  65. assert device_type.lower() in SUPPORTED_DEVICE_TYPE
  66. return device_type, device_ids
  67. def update_device_num(device, num):
  68. device_type, device_ids = parse_device(device)
  69. if device_ids:
  70. assert len(device_ids) >= num
  71. return _constr_device(device_type, device_ids[:num])
  72. else:
  73. return _constr_device(device_type, device_ids)
  74. def set_env_for_device(device):
  75. def _set(envs):
  76. for key, val in envs.items():
  77. os.environ[key] = val
  78. logging.debug(f"{key} has been set to {val}.")
  79. device_type, device_ids = parse_device(device)
  80. if device_type.lower() in ["gpu", "xpu", "npu", "mlu", "gcu"]:
  81. if device_type.lower() == "gpu" and paddle.is_compiled_with_rocm():
  82. envs = {"FLAGS_conv_workspace_size_limit": "2000"}
  83. _set(envs)
  84. if device_type.lower() == "npu":
  85. envs = {
  86. "FLAGS_npu_jit_compile": "0",
  87. "FLAGS_use_stride_kernel": "0",
  88. "FLAGS_allocator_strategy": "auto_growth",
  89. "CUSTOM_DEVICE_BLACK_LIST": "pad3d,pad3d_grad,set_value,set_value_with_tensor",
  90. "FLAGS_npu_scale_aclnn": "True",
  91. "FLAGS_npu_split_aclnn": "True",
  92. }
  93. _set(envs)
  94. if device_type.lower() == "xpu":
  95. envs = {
  96. "BKCL_FORCE_SYNC": "1",
  97. "BKCL_TIMEOUT": "1800",
  98. "FLAGS_use_stride_kernel": "0",
  99. "XPU_BLACK_LIST": "pad3d",
  100. }
  101. _set(envs)
  102. if device_type.lower() == "mlu":
  103. envs = {"FLAGS_use_stride_kernel": "0"}
  104. _set(envs)
  105. if device_type.lower() == "gcu":
  106. envs = {"FLAGS_use_stride_kernel": "0"}
  107. _set(envs)
  108. def check_supported_device(device, model_name):
  109. device_type, device_ids = parse_device(device)
  110. if device_type == "dcu":
  111. assert (
  112. model_name in DCU_WHITELIST
  113. ), f"The DCU device does not yet support `{model_name}` model!"
  114. elif device_type == "mlu":
  115. assert (
  116. model_name in MLU_WHITELIST
  117. ), f"The MLU device does not yet support `{model_name}` model!"
  118. elif device_type == "npu":
  119. assert (
  120. model_name in NPU_WHITELIST
  121. ), f"The NPU device does not yet support `{model_name}` model!"
  122. elif device_type == "xpu":
  123. assert (
  124. model_name in XPU_WHITELIST
  125. ), f"The XPU device does not yet support `{model_name}` model!"
  126. elif device_type == "gcu":
  127. assert (
  128. model_name in GCU_WHITELIST
  129. ), f"The GCU device does not yet support `{model_name}` model!"