ray_utils.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. import pickle
  2. from typing import List, Optional, Tuple
  3. from aphrodite.common.config import ParallelConfig
  4. from aphrodite.common.utils import get_ip, is_hip, is_xpu
  5. from aphrodite.task_handler.worker_base import WorkerWrapperBase
  6. try:
  7. import ray
  8. class RayWorkerWrapper(WorkerWrapperBase):
  9. """Ray wrapper for aphrodite.task_handler.Worker, allowing Worker to be
  10. lazliy initialized after Ray sets CUDA_VISIBLE_DEVICES."""
  11. def __init__(self, *args, **kwargs) -> None:
  12. super().__init__(*args, **kwargs)
  13. # Since the compiled DAG runs a main execution
  14. # in a different thread that calls cuda.set_device.
  15. # The flag indicates is set_device is called on
  16. # that thread.
  17. self.compiled_dag_cuda_device_set = False
  18. def get_node_ip(self) -> str:
  19. return get_ip()
  20. def get_node_and_gpu_ids(self) -> Tuple[str, List[int]]:
  21. node_id = ray.get_runtime_context().get_node_id()
  22. gpu_ids = ray.get_gpu_ids()
  23. return node_id, gpu_ids
  24. def execute_model_compiled_dag_remote(self, ignored):
  25. """Used only when compiled DAG is enabled."""
  26. import torch
  27. if not self.compiled_dag_cuda_device_set:
  28. torch.cuda.set_device(self.worker.device)
  29. self.compiled_dag_cuda_device_set = True
  30. output = self.worker.execute_model()
  31. output = pickle.dumps(output)
  32. return output
  33. ray_import_err = None
  34. except ImportError as e:
  35. ray = None # type: ignore
  36. ray_import_err = e
  37. RayWorkerWrapper = None # type: ignore
  38. def ray_is_available() -> bool:
  39. """Returns True if Ray is available."""
  40. return ray is not None
  41. def assert_ray_available():
  42. """Raise an exception if Ray is not available."""
  43. if ray is None:
  44. raise ValueError("Failed to import Ray, please install Ray with "
  45. "`pip install ray`.") from ray_import_err
  46. def initialize_ray_cluster(
  47. parallel_config: ParallelConfig,
  48. ray_address: Optional[str] = None,
  49. ):
  50. """Initialize the distributed cluster with Ray.
  51. it will connect to the Ray cluster and create a placement group
  52. for the workers, which includes the specification of the resources
  53. for each distributed worker.
  54. Args:
  55. parallel_config: The configurations for parallel execution.
  56. ray_address: The address of the Ray cluster. If None, uses
  57. the default Ray cluster address.
  58. """
  59. assert_ray_available()
  60. # Connect to a ray cluster.
  61. if is_hip() or is_xpu():
  62. ray.init(address=ray_address,
  63. ignore_reinit_error=True,
  64. num_gpus=parallel_config.world_size)
  65. else:
  66. ray.init(address=ray_address, ignore_reinit_error=True)
  67. if parallel_config.placement_group:
  68. # Placement group is already set.
  69. return
  70. # Create placement group for worker processes
  71. current_placement_group = ray.util.get_current_placement_group()
  72. if current_placement_group:
  73. # We are in a placement group
  74. bundles = current_placement_group.bundle_specs
  75. # Verify that we can use the placement group.
  76. gpu_bundles = 0
  77. for bundle in bundles:
  78. bundle_gpus = bundle.get("GPU", 0)
  79. if bundle_gpus > 1:
  80. raise ValueError(
  81. "Placement group bundle cannot have more than 1 GPU.")
  82. if bundle_gpus:
  83. gpu_bundles += 1
  84. if parallel_config.world_size > gpu_bundles:
  85. raise ValueError(
  86. "The number of required GPUs exceeds the total number of "
  87. "available GPUs in the placement group.")
  88. else:
  89. num_gpus_in_cluster = ray.cluster_resources().get("GPU", 0)
  90. if parallel_config.world_size > num_gpus_in_cluster:
  91. raise ValueError(
  92. "The number of required GPUs exceeds the total number of "
  93. "available GPUs in the cluster.")
  94. # Create a new placement group
  95. placement_group_specs = ([{"GPU": 1}] * parallel_config.world_size)
  96. current_placement_group = ray.util.placement_group(
  97. placement_group_specs)
  98. # Wait until PG is ready - this will block until all
  99. # requested resources are available, and will timeout
  100. # if they cannot be provisioned.
  101. ray.get(current_placement_group.ready(), timeout=1800)
  102. # Set the placement group in the parallel config
  103. parallel_config.placement_group = current_placement_group