device.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  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. SUPPORTED_DEVICE_TYPE = ["cpu", "gpu", "xpu", "npu", "mlu", "gcu"]
  20. def _constr_device(device_type, device_ids):
  21. if device_ids:
  22. device_ids = ",".join(map(str, device_ids))
  23. return f"{device_type}:{device_ids}"
  24. else:
  25. return f"{device_type}"
  26. def get_default_device():
  27. avail_gpus = GPUtil.getAvailable()
  28. if not avail_gpus:
  29. # maybe edge devices like Jetson
  30. if os.path.exists("/etc/nv_tegra_release"):
  31. avail_gpus = [0]
  32. logging.info(
  33. "Detected that the current device is a Jetson edge device. The default behavior will be to use GPU: 0"
  34. )
  35. if not avail_gpus:
  36. return "cpu"
  37. else:
  38. return _constr_device("gpu", [avail_gpus[0]])
  39. def parse_device(device):
  40. """parse_device"""
  41. # According to https://www.paddlepaddle.org.cn/documentation/docs/zh/api/paddle/device/set_device_cn.html
  42. parts = device.split(":")
  43. if len(parts) > 2:
  44. raise ValueError(f"Invalid device: {device}")
  45. if len(parts) == 1:
  46. device_type, device_ids = parts[0], None
  47. else:
  48. device_type, device_ids = parts
  49. device_ids = device_ids.split(",")
  50. for device_id in device_ids:
  51. if not device_id.isdigit():
  52. raise ValueError(
  53. f"Device ID must be an integer. Invalid device ID: {device_id}"
  54. )
  55. device_ids = list(map(int, device_ids))
  56. device_type = device_type.lower()
  57. # raise_unsupported_device_error(device_type, SUPPORTED_DEVICE_TYPE)
  58. assert device_type.lower() in SUPPORTED_DEVICE_TYPE
  59. return device_type, device_ids
  60. def update_device_num(device, num):
  61. device_type, device_ids = parse_device(device)
  62. if device_ids:
  63. assert len(device_ids) >= num
  64. return _constr_device(device_type, device_ids[:num])
  65. else:
  66. return _constr_device(device_type, device_ids)
  67. def set_env_for_device(device):
  68. def _set(envs):
  69. for key, val in envs.items():
  70. os.environ[key] = val
  71. logging.debug(f"{key} has been set to {val}.")
  72. device_type, device_ids = parse_device(device)
  73. if device_type.lower() in ["gpu", "xpu", "npu", "mlu", "gcu"]:
  74. if device_type.lower() == "gpu" and paddle.is_compiled_with_rocm():
  75. envs = {"FLAGS_conv_workspace_size_limit": "2000"}
  76. _set(envs)
  77. if device_type.lower() == "npu":
  78. envs = {
  79. "FLAGS_npu_jit_compile": "0",
  80. "FLAGS_use_stride_kernel": "0",
  81. "FLAGS_allocator_strategy": "auto_growth",
  82. "CUSTOM_DEVICE_BLACK_LIST": "pad3d,pad3d_grad,set_value,set_value_with_tensor",
  83. "FLAGS_npu_scale_aclnn": "True",
  84. "FLAGS_npu_split_aclnn": "True",
  85. }
  86. _set(envs)
  87. if device_type.lower() == "xpu":
  88. envs = {
  89. "BKCL_FORCE_SYNC": "1",
  90. "BKCL_TIMEOUT": "1800",
  91. "FLAGS_use_stride_kernel": "0",
  92. "XPU_BLACK_LIST": "pad3d",
  93. }
  94. _set(envs)
  95. if device_type.lower() == "mlu":
  96. envs = {"FLAGS_use_stride_kernel": "0"}
  97. _set(envs)
  98. if device_type.lower() == "gcu":
  99. envs = {"FLAGS_use_stride_kernel": "0"}
  100. _set(envs)