ray_utils.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  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. except ImportError as e:
  34. ray = None # type: ignore
  35. RayWorkerWrapper = None # type: ignore
  36. def initialize_ray_cluster(
  37. parallel_config: ParallelConfig,
  38. ray_address: Optional[str] = None,
  39. ):
  40. """Initialize the distributed cluster with Ray.
  41. it will connect to the Ray cluster and create a placement group
  42. for the workers, which includes the specification of the resources
  43. for each distributed worker.
  44. Args:
  45. parallel_config: The configurations for parallel execution.
  46. ray_address: The address of the Ray cluster. If None, uses
  47. the default Ray cluster address.
  48. """
  49. if ray is None:
  50. raise ImportError(
  51. "Ray is not installed. Please install Ray to use multi-node "
  52. "serving. You can install Ray by running "
  53. "`pip install aphrodite-engine[\"ray\"]`.")
  54. # Connect to a ray cluster.
  55. if is_hip() or is_xpu():
  56. ray.init(address=ray_address,
  57. ignore_reinit_error=True,
  58. num_gpus=parallel_config.world_size)
  59. else:
  60. ray.init(address=ray_address, ignore_reinit_error=True)
  61. if parallel_config.placement_group:
  62. # Placement group is already set.
  63. return
  64. # Create placement group for worker processes
  65. current_placement_group = ray.util.get_current_placement_group()
  66. if current_placement_group:
  67. # We are in a placement group
  68. bundles = current_placement_group.bundle_specs
  69. # Verify that we can use the placement group.
  70. gpu_bundles = 0
  71. for bundle in bundles:
  72. bundle_gpus = bundle.get("GPU", 0)
  73. if bundle_gpus > 1:
  74. raise ValueError(
  75. "Placement group bundle cannot have more than 1 GPU.")
  76. if bundle_gpus:
  77. gpu_bundles += 1
  78. if parallel_config.world_size > gpu_bundles:
  79. raise ValueError(
  80. "The number of required GPUs exceeds the total number of "
  81. "available GPUs in the placement group.")
  82. else:
  83. num_gpus_in_cluster = ray.cluster_resources().get("GPU", 0)
  84. if parallel_config.world_size > num_gpus_in_cluster:
  85. raise ValueError(
  86. "The number of required GPUs exceeds the total number of "
  87. "available GPUs in the cluster.")
  88. # Create a new placement group
  89. placement_group_specs = ([{"GPU": 1}] * parallel_config.world_size)
  90. current_placement_group = ray.util.placement_group(
  91. placement_group_specs)
  92. # Wait until PG is ready - this will block until all
  93. # requested resources are available, and will timeout
  94. # if they cannot be provisioned.
  95. ray.get(current_placement_group.ready(), timeout=1800)
  96. # Set the placement group in the parallel config
  97. parallel_config.placement_group = current_placement_group