ray_gpu_executor.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. import asyncio
  2. import os
  3. import pickle
  4. from collections import defaultdict
  5. from typing import TYPE_CHECKING, Any, Dict, List, Optional, Set, Tuple
  6. from loguru import logger
  7. from aphrodite.common.sequence import SamplerOutput, SequenceGroupMetadata
  8. from aphrodite.common.utils import (get_distributed_init_method, get_ip,
  9. get_open_port, make_async)
  10. from aphrodite.engine.ray_tools import RayWorkerWrapper, ray
  11. from aphrodite.executor.executor_base import ExecutorAsyncBase, ExecutorBase
  12. from aphrodite.lora.request import LoRARequest
  13. if ray is not None:
  14. from ray.util.scheduling_strategies import PlacementGroupSchedulingStrategy
  15. if TYPE_CHECKING:
  16. from ray.util.placement_group import PlacementGroup
  17. # If the env var is set, it uses the Ray's compiled DAG API
  18. # which optimizes the control plane overhead.
  19. # Run Aphrodite with APHRODITE_USE_RAY_COMPILED_DAG=1 to enable it.
  20. USE_RAY_COMPILED_DAG = bool(os.getenv("APHRODITE_USE_RAY_COMPILED_DAG", 0))
  21. class RayGPUExecutor(ExecutorBase):
  22. def _init_executor(self) -> None:
  23. assert (not self.speculative_config
  24. ), "Speculative decoding not yet supported for RayGPU backend."
  25. assert self.parallel_config.worker_use_ray
  26. placement_group = self.parallel_config.placement_group
  27. # Disable Ray usage stats collection.
  28. ray_usage = os.environ.get("RAY_USAGE_STATS_ENABLED", "0")
  29. if ray_usage != "1":
  30. os.environ["RAY_USAGE_STATS_ENABLED"] = "0"
  31. # Create the parallel GPU workers.
  32. self._init_workers_ray(placement_group)
  33. self.forward_dag = None
  34. if USE_RAY_COMPILED_DAG:
  35. self.forward_dag = self._compiled_ray_dag()
  36. def _configure_ray_workers_use_nsight(self,
  37. ray_remote_kwargs) -> Dict[str, Any]:
  38. # If nsight profiling is enabled, we need to set the profiling
  39. # configuration for the ray workers as runtime env.
  40. runtime_env = ray_remote_kwargs.setdefault("runtime_env", {})
  41. runtime_env.update({
  42. "nsight": {
  43. "t": "cuda,cudnn,cublas",
  44. "o": "'worker_process_%p'",
  45. "cuda-graph-trace": "node",
  46. }
  47. })
  48. return ray_remote_kwargs
  49. def _init_workers_ray(self, placement_group: "PlacementGroup",
  50. **ray_remote_kwargs):
  51. if self.parallel_config.tensor_parallel_size == 1:
  52. # For single GPU case, we use a ray worker with constrained memory.
  53. num_gpus = self.cache_config.gpu_memory_utilization
  54. else:
  55. # Otherwise, the ray workers are allocated with a full GPU.
  56. num_gpus = 1
  57. # The driver dummy worker does not actually use any resources.
  58. # It holds the resource for the driver worker.
  59. self.driver_dummy_worker: RayWorkerWrapper = None
  60. # The remaining workers are the actual ray actors.
  61. self.workers: List[RayWorkerWrapper] = []
  62. if self.parallel_config.ray_workers_use_nsight:
  63. ray_remote_kwargs = self._configure_ray_workers_use_nsight(
  64. ray_remote_kwargs)
  65. # Create the workers.
  66. driver_ip = get_ip()
  67. for bundle_id, bundle in enumerate(placement_group.bundle_specs):
  68. if not bundle.get("GPU", 0):
  69. continue
  70. scheduling_strategy = PlacementGroupSchedulingStrategy(
  71. placement_group=placement_group,
  72. placement_group_capture_child_tasks=True,
  73. placement_group_bundle_index=bundle_id,
  74. )
  75. worker = ray.remote(
  76. num_cpus=0,
  77. num_gpus=num_gpus,
  78. scheduling_strategy=scheduling_strategy,
  79. **ray_remote_kwargs,
  80. )(RayWorkerWrapper).remote(
  81. worker_module_name="aphrodite.task_handler.worker",
  82. worker_class_name="Worker",
  83. )
  84. worker_ip = ray.get(worker.get_node_ip.remote())
  85. if worker_ip == driver_ip and self.driver_dummy_worker is None:
  86. # If the worker is on the same node as the driver, we use it
  87. # as the resource holder for the driver process.
  88. self.driver_dummy_worker = worker
  89. self.driver_worker = RayWorkerWrapper(
  90. worker_module_name="aphrodite.task_handler.worker",
  91. worker_class_name="Worker",
  92. )
  93. else:
  94. # Else, added to the list of workers.
  95. self.workers.append(worker)
  96. if self.driver_dummy_worker is None:
  97. raise ValueError(
  98. "Ray does not allocate any GPUs on the driver node. Consider "
  99. "adjusting the Ray placement group or running the driver on a "
  100. "GPU node.")
  101. worker_node_and_gpu_ids = self._run_workers("get_node_and_gpu_ids",
  102. use_dummy_driver=True)
  103. node_workers = defaultdict(list)
  104. node_gpus = defaultdict(list)
  105. for i, (node_id, gpu_ids) in enumerate(worker_node_and_gpu_ids):
  106. node_workers[node_id].append(i)
  107. node_gpus[node_id].extend(gpu_ids)
  108. for node_id, gpu_ids in node_gpus.items():
  109. node_gpus[node_id] = sorted(gpu_ids)
  110. # Set CUDA_VISIBLE_DEVICES for the driver and workers.
  111. all_args_to_update_environment_variables = []
  112. for (node_id, _) in worker_node_and_gpu_ids:
  113. all_args_to_update_environment_variables.append([{
  114. "CUDA_VISIBLE_DEVICES":
  115. ",".join(map(str, node_gpus[node_id])),
  116. }])
  117. distributed_init_method = get_distributed_init_method(
  118. driver_ip, get_open_port())
  119. def collect_arg_helper_func(**kwargs):
  120. return kwargs
  121. init_worker_all_kwargs = []
  122. for rank, (node_id, _) in enumerate(worker_node_and_gpu_ids):
  123. local_rank = node_workers[node_id].index(rank)
  124. init_worker_all_kwargs.append(
  125. collect_arg_helper_func(
  126. model_config=self.model_config,
  127. parallel_config=self.parallel_config,
  128. scheduler_config=self.scheduler_config,
  129. device_config=self.device_config,
  130. cache_config=self.cache_config,
  131. local_rank=local_rank,
  132. rank=rank,
  133. distributed_init_method=distributed_init_method,
  134. lora_config=self.lora_config,
  135. vision_language_config=self.vision_language_config,
  136. ))
  137. self._run_workers("init_worker", all_kwargs=init_worker_all_kwargs)
  138. self._run_workers("init_device")
  139. self._run_workers(
  140. "load_model",
  141. max_concurrent_workers=self.parallel_config.
  142. max_parallel_loading_workers,
  143. )
  144. def determine_num_available_blocks(self) -> tuple[int, int]:
  145. """Determine the number of available KV blocks.
  146. This invokes `determine_num_available_blocks` on each worker and takes
  147. the min of the results, guaranteeing that the selected cache sizes are
  148. compatible with all workers.
  149. Returns:
  150. - tuple[num_gpu_blocks, num_cpu_blocks]
  151. """
  152. # Get the maximum number of blocks that can be allocated on GPU and CPU.
  153. num_blocks = self._run_workers("determine_num_available_blocks", )
  154. # Since we use a shared centralized controller, we take the minimum
  155. # number of blocks across all workers to make sure all the memory
  156. # operators can be applied to all workers.
  157. num_gpu_blocks = min(b[0] for b in num_blocks)
  158. num_cpu_blocks = min(b[1] for b in num_blocks)
  159. return num_gpu_blocks, num_cpu_blocks
  160. def initialize_cache(self, num_gpu_blocks: int,
  161. num_cpu_blocks: int) -> None:
  162. """Initialize the KV cache in all workers.
  163. """
  164. # NOTE: We log here to avoid multiple logs when number of workers is
  165. # greater than one. We could log in the engine, but not all executors
  166. # have GPUs.
  167. logger.info(f"# GPU blocks: {num_gpu_blocks}, "
  168. f"# CPU blocks: {num_cpu_blocks}")
  169. logger.info(
  170. f"Minimum concurrency: {num_gpu_blocks * self.cache_config.block_size / self.scheduler_config.max_model_len:.2f}x" # noqa: E501
  171. )
  172. self.cache_config.num_gpu_blocks = num_gpu_blocks
  173. self.cache_config.num_cpu_blocks = num_cpu_blocks
  174. self._run_workers("initialize_cache",
  175. num_gpu_blocks=num_gpu_blocks,
  176. num_cpu_blocks=num_cpu_blocks)
  177. def execute_model(self,
  178. seq_group_metadata_list: List[SequenceGroupMetadata],
  179. blocks_to_swap_in: Dict[int, int],
  180. blocks_to_swap_out: Dict[int, int],
  181. blocks_to_copy: Dict[int, List[int]],
  182. num_lookahead_slots: int = 0) -> List[SamplerOutput]:
  183. all_outputs = self._run_workers(
  184. "execute_model",
  185. driver_kwargs={
  186. "seq_group_metadata_list": seq_group_metadata_list,
  187. "blocks_to_swap_in": blocks_to_swap_in,
  188. "blocks_to_swap_out": blocks_to_swap_out,
  189. "blocks_to_copy": blocks_to_copy,
  190. },
  191. use_ray_compiled_dag=USE_RAY_COMPILED_DAG)
  192. # Only the driver worker returns the sampling results.
  193. output = all_outputs[0]
  194. return output
  195. def add_lora(self, lora_request: LoRARequest) -> bool:
  196. assert lora_request.lora_int_id > 0, "lora_id must be greater than 0."
  197. return self._run_workers(
  198. "add_lora",
  199. lora_request=lora_request,
  200. )
  201. def remove_lora(self, lora_id: int) -> bool:
  202. assert lora_id > 0, "lora_id must be greater than 0."
  203. return self._run_workers(
  204. "remove_lora",
  205. lora_id=lora_id,
  206. )
  207. def list_loras(self) -> Set[int]:
  208. return self._run_workers("list_loras")
  209. def _run_workers(
  210. self,
  211. method: str,
  212. *args,
  213. driver_args: Optional[Tuple[Any]] = None,
  214. driver_kwargs: Optional[Dict[str, Any]] = None,
  215. all_args: Optional[List[List[Any]]] = None,
  216. all_kwargs: Optional[List[Dict[str, Any]]] = None,
  217. use_dummy_driver: bool = False,
  218. max_concurrent_workers: Optional[int] = None,
  219. use_ray_compiled_dag: bool = False,
  220. **kwargs,
  221. ) -> Any:
  222. """Runs the given method on all workers."""
  223. if driver_args is None:
  224. driver_args = args
  225. if driver_kwargs is None:
  226. driver_kwargs = kwargs
  227. # For MyPy type checking
  228. assert driver_args is not None
  229. assert driver_kwargs is not None
  230. if all_args is None:
  231. all_args = [driver_args] + [args] * len(self.workers)
  232. if all_kwargs is None:
  233. all_kwargs = [driver_kwargs] + [kwargs] * len(self.workers)
  234. assert all_args is not None
  235. assert all_kwargs is not None
  236. if max_concurrent_workers:
  237. raise NotImplementedError(
  238. "max_concurrent_workers is not supported yet.")
  239. if use_ray_compiled_dag:
  240. # Right now, compiled DAG can only accept a single
  241. # input. TODO: Fix it.
  242. output_channels = self.forward_dag.execute(1)
  243. else:
  244. # Start the ray workers first.
  245. ray_worker_outputs = [
  246. worker.execute_method.remote(method, *worker_args,
  247. **worker_kwargs)
  248. for (worker, worker_args, worker_kwargs
  249. ) in zip(self.workers, all_args[1:], all_kwargs[1:])
  250. ]
  251. if driver_args is None:
  252. driver_args = args
  253. if driver_kwargs is None:
  254. driver_kwargs = kwargs
  255. # Start the driver worker after all the ray workers.
  256. if not use_dummy_driver:
  257. driver_worker_output = self.driver_worker.execute_method(
  258. method, *all_args[0], **all_kwargs[0])
  259. else:
  260. driver_worker_output = ray.get(
  261. self.driver_dummy_worker.execute_method.remote(
  262. method, *all_args[0], **all_kwargs[0]))
  263. # Get the results of the ray workers.
  264. if self.workers:
  265. if use_ray_compiled_dag:
  266. try:
  267. ray_worker_outputs = [
  268. pickle.loads(chan.begin_read())
  269. for chan in output_channels
  270. ]
  271. finally:
  272. # Has to call end_read in order to reuse the DAG.
  273. for chan in output_channels:
  274. chan.end_read()
  275. else:
  276. ray_worker_outputs = ray.get(ray_worker_outputs)
  277. return [driver_worker_output] + ray_worker_outputs
  278. def _compiled_ray_dag(self):
  279. import pkg_resources
  280. required_version = "2.9"
  281. current_version = pkg_resources.get_distribution("ray").version
  282. if current_version < required_version:
  283. raise ValueError(f"Ray version {required_version} or greater is "
  284. f"required, but found {current_version}")
  285. from ray.dag import InputNode, MultiOutputNode
  286. assert self.parallel_config.worker_use_ray
  287. # Right now, compiled DAG requires at least 1 arg. We send
  288. # a dummy value for now. It will be fixed soon.
  289. with InputNode() as input_data:
  290. forward_dag = MultiOutputNode([
  291. worker.execute_model_compiled_dag_remote.bind(input_data)
  292. for worker in self.workers
  293. ])
  294. return forward_dag.experimental_compile()
  295. def check_health(self) -> None:
  296. """Raises an error if engine is unhealthy."""
  297. self._check_if_any_actor_is_dead()
  298. def _check_if_any_actor_is_dead(self):
  299. if not self.workers:
  300. return
  301. dead_actors = []
  302. for actor in self.workers:
  303. actor_state = ray.state.actors(actor._ray_actor_id.hex()) # pylint: disable=protected-access
  304. if actor_state["State"] == "DEAD":
  305. dead_actors.append(actor)
  306. if dead_actors:
  307. raise RuntimeError("At least one Worker is dead. "
  308. f"Dead Workers: {dead_actors}. ")
  309. class RayGPUExecutorAsync(RayGPUExecutor, ExecutorAsyncBase):
  310. async def _run_workers_async(
  311. self,
  312. method: str,
  313. *args,
  314. driver_args: Optional[List[Any]] = None,
  315. driver_kwargs: Optional[Dict[str, Any]] = None,
  316. **kwargs,
  317. ) -> Any:
  318. """Runs the given method on all workers."""
  319. coros = []
  320. if driver_args is None:
  321. driver_args = args
  322. if driver_kwargs is None:
  323. driver_kwargs = kwargs
  324. # Run the driver worker asynchronously.
  325. def helper():
  326. return self.driver_worker.execute_method(method, *driver_args,
  327. **driver_kwargs)
  328. driver_executor = make_async(helper)
  329. coros.append(driver_executor())
  330. # Run the ray workers asynchronously.
  331. for worker in self.workers:
  332. coros.append(worker.execute_method.remote(method, *args, **kwargs))
  333. all_outputs = await asyncio.gather(*coros)
  334. return all_outputs
  335. async def execute_model_async(
  336. self,
  337. seq_group_metadata_list: List[SequenceGroupMetadata],
  338. blocks_to_swap_in: Dict[int, int],
  339. blocks_to_swap_out: Dict[int, int],
  340. blocks_to_copy: Dict[int, List[int]],
  341. num_lookahead_slots: int = 0,
  342. ) -> SamplerOutput:
  343. all_outputs = await self._run_workers_async(
  344. "execute_model",
  345. driver_kwargs={
  346. "seq_group_metadata_list": seq_group_metadata_list,
  347. "blocks_to_swap_in": blocks_to_swap_in,
  348. "blocks_to_swap_out": blocks_to_swap_out,
  349. "blocks_to_copy": blocks_to_copy,
  350. "num_lookahead_slots": num_lookahead_slots,
  351. })
  352. # Only the driver worker returns the sampling results.
  353. output = all_outputs[0]
  354. return output