ray_utils.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. from typing import List, Optional, Tuple, Union
  2. from aphrodite.common.config import ParallelConfig
  3. from aphrodite.common.sequence import ExecuteModelRequest, IntermediateTensors
  4. from aphrodite.common.utils import get_ip, is_hip, is_xpu
  5. from aphrodite.platforms import current_platform
  6. from aphrodite.task_handler.worker_base import WorkerWrapperBase
  7. try:
  8. import ray
  9. class RayWorkerWrapper(WorkerWrapperBase):
  10. """Ray wrapper for aphrodite.task_handler.Worker, allowing Worker to be
  11. lazliy initialized after Ray sets CUDA_VISIBLE_DEVICES."""
  12. def __init__(self, *args, **kwargs) -> None:
  13. super().__init__(*args, **kwargs)
  14. # Since the compiled DAG runs a main execution
  15. # in a different thread that calls cuda.set_device.
  16. # The flag indicates is set_device is called on
  17. # that thread.
  18. self.compiled_dag_cuda_device_set = False
  19. def get_node_ip(self) -> str:
  20. return get_ip()
  21. def get_node_and_gpu_ids(self) -> Tuple[str, List[int]]:
  22. node_id = ray.get_runtime_context().get_node_id()
  23. gpu_ids = ray.get_gpu_ids()
  24. return node_id, gpu_ids
  25. def execute_model_spmd(
  26. self, req_or_tuple: Union[ExecuteModelRequest,
  27. Tuple[ExecuteModelRequest,
  28. IntermediateTensors]]):
  29. """Execute model in SPMD fashion: used only when SPMD worker and
  30. compiled DAG are both enabled.
  31. Args:
  32. req_or_tuple: The request to execute the model, or a tuple
  33. containing the request and intermediate tensors.
  34. """
  35. # TODO: This is needed right now because Ray DAG executes
  36. # on a background thread, so we need to reset torch's current
  37. # device.
  38. import torch
  39. if not self.compiled_dag_cuda_device_set:
  40. torch.cuda.set_device(self.worker.device)
  41. self.compiled_dag_cuda_device_set = True
  42. if isinstance(req_or_tuple, tuple):
  43. execute_model_req, intermediate_tensors = req_or_tuple
  44. else:
  45. execute_model_req = req_or_tuple
  46. intermediate_tensors = None
  47. output = self.worker._execute_model_spmd(execute_model_req,
  48. intermediate_tensors)
  49. if isinstance(output, IntermediateTensors):
  50. return execute_model_req, output
  51. return output
  52. ray_import_err = None
  53. except ImportError as e:
  54. ray = None # type: ignore
  55. ray_import_err = e
  56. RayWorkerWrapper = None # type: ignore
  57. def ray_is_available() -> bool:
  58. """Returns True if Ray is available."""
  59. return ray is not None
  60. def assert_ray_available():
  61. """Raise an exception if Ray is not available."""
  62. if ray is None:
  63. raise ValueError("Failed to import Ray, please install Ray with "
  64. "`pip install ray`.") from ray_import_err
  65. def initialize_ray_cluster(
  66. parallel_config: ParallelConfig,
  67. ray_address: Optional[str] = None,
  68. ):
  69. """Initialize the distributed cluster with Ray.
  70. it will connect to the Ray cluster and create a placement group
  71. for the workers, which includes the specification of the resources
  72. for each distributed worker.
  73. Args:
  74. parallel_config: The configurations for parallel execution.
  75. ray_address: The address of the Ray cluster. If None, uses
  76. the default Ray cluster address.
  77. """
  78. assert_ray_available()
  79. # Connect to a ray cluster.
  80. if is_hip() or is_xpu():
  81. ray.init(address=ray_address,
  82. ignore_reinit_error=True,
  83. num_gpus=parallel_config.world_size)
  84. else:
  85. ray.init(address=ray_address, ignore_reinit_error=True)
  86. if parallel_config.placement_group:
  87. # Placement group is already set.
  88. return
  89. device_str = "GPU" if not current_platform.is_tpu() else "TPU"
  90. # Create placement group for worker processes
  91. current_placement_group = ray.util.get_current_placement_group()
  92. if current_placement_group:
  93. # We are in a placement group
  94. bundles = current_placement_group.bundle_specs
  95. # Verify that we can use the placement group.
  96. device_bundles = 0
  97. for bundle in bundles:
  98. bundle_devices = bundle.get(device_str, 0)
  99. if bundle_devices > 1:
  100. raise ValueError(
  101. "Placement group bundle cannot have more than 1 "
  102. f"{device_str}.")
  103. if bundle_devices:
  104. device_bundles += 1
  105. if parallel_config.world_size > device_bundles:
  106. raise ValueError(
  107. f"The number of required {device_str}s exceeds the total "
  108. f"number of available {device_str}s in the placement group."
  109. f"Required number of devices: {parallel_config.world_size}. "
  110. f"Total number of devices: {device_bundles}.")
  111. else:
  112. num_devices_in_cluster = ray.cluster_resources().get(device_str, 0)
  113. if parallel_config.world_size > num_devices_in_cluster:
  114. raise ValueError(
  115. f"The number of required {device_str}s exceeds the total "
  116. f"number of available {device_str}s in the placement group.")
  117. # Create a new placement group
  118. placement_group_specs = ([{
  119. device_str: 1
  120. }] * parallel_config.world_size)
  121. current_placement_group = ray.util.placement_group(
  122. placement_group_specs)
  123. # Wait until PG is ready - this will block until all
  124. # requested resources are available, and will timeout
  125. # if they cannot be provisioned.
  126. ray.get(current_placement_group.ready(), timeout=1800)
  127. # Set the placement group in the parallel config
  128. parallel_config.placement_group = current_placement_group