ray_gpu_executor.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. import asyncio
  2. import os
  3. from collections import defaultdict
  4. from itertools import islice, repeat
  5. from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple
  6. import msgspec
  7. from loguru import logger
  8. from aphrodite.common.sequence import ExecuteModelRequest, SamplerOutput
  9. from aphrodite.common.utils import (_run_task_with_lock,
  10. get_aphrodite_instance_id,
  11. get_distributed_init_method, get_ip,
  12. get_open_port, make_async)
  13. from aphrodite.executor.distributed_gpu_executor import ( # yapf: disable
  14. DistributedGPUExecutor, DistributedGPUExecutorAsync)
  15. from aphrodite.executor.msgspec_utils import encode_hook
  16. from aphrodite.executor.ray_utils import RayWorkerWrapper, ray
  17. if ray is not None:
  18. from ray.util.scheduling_strategies import PlacementGroupSchedulingStrategy
  19. if TYPE_CHECKING:
  20. from ray.util.placement_group import PlacementGroup
  21. # If the env var is set, it uses the Ray's compiled DAG API
  22. # which optimizes the control plane overhead.
  23. # Run Aphrodite with APHRODITE_USE_RAY_COMPILED_DAG=1 to enable it.
  24. APHRODITE_USE_RAY_COMPILED_DAG = bool(
  25. os.getenv("APHRODITE_USE_RAY_COMPILED_DAG", 0))
  26. APHRODITE_TRACE_FUNCTION = int(os.getenv("APHRODITE_TRACE_FUNCTION", 0))
  27. APHRODITE_USE_RAY_SPMD_WORKER = bool(
  28. os.getenv("APHRODITE_USE_RAY_SPMD_WORKER", 0))
  29. APHRODITE_USE_RAY_COMPILED_DAG_NCCL_CHANNEL = bool(
  30. int(os.getenv("APHRODITE_USE_RAY_COMPILED_DAG_NCCL_CHANNEL", 1)))
  31. class RayGPUExecutor(DistributedGPUExecutor):
  32. uses_ray: bool = True
  33. def _init_executor(self) -> None:
  34. self.forward_dag: Optional["ray.dag.CompiledDAG"] = None
  35. # If the env var is set, it uses the Ray's compiled DAG API
  36. # which optimizes the control plane overhead.
  37. # Run Aphrodite with APHRODITE_USE_RAY_COMPILED_DAG=1 to enable it.
  38. # Currently, this requires USE_RAY_SPMD_WORKER=True.
  39. self.use_ray_compiled_dag = APHRODITE_USE_RAY_COMPILED_DAG
  40. # If the env var is set, then we do not distinguish between the
  41. # "driver worker" vs other workers. Also, the rank 0 worker will
  42. # be executed in a remote Ray worker. Currently this requires
  43. # USE_RAY_COMPILED_DAG=True.
  44. self.use_ray_spmd_worker = APHRODITE_USE_RAY_SPMD_WORKER
  45. if self.use_ray_compiled_dag:
  46. assert self.use_ray_spmd_worker, (
  47. "APHRODITE_USE_RAY_COMPILED_DAG=1 requires "
  48. "APHRODITE_USE_RAY_SPMD_WORKER=1")
  49. if self.use_ray_spmd_worker:
  50. # TODO: Support SPMD worker for non-DAG Ray executor.
  51. assert self.use_ray_compiled_dag, (
  52. "APHRODITE_USE_RAY_SPMD_WORKER=1 requires "
  53. "APHRODITE_USE_RAY_COMPILED_DAG=1")
  54. assert self.uses_ray
  55. placement_group = self.parallel_config.placement_group
  56. # Disable Ray usage stats collection.
  57. ray_usage = os.environ.get("RAY_USAGE_STATS_ENABLED", "0")
  58. if ray_usage != "1":
  59. os.environ["RAY_USAGE_STATS_ENABLED"] = "0"
  60. # Create the parallel GPU workers.
  61. self._init_workers_ray(placement_group)
  62. self.input_encoder = msgspec.msgpack.Encoder(enc_hook=encode_hook)
  63. self.output_decoder = msgspec.msgpack.Decoder(
  64. Optional[List[SamplerOutput]])
  65. def shutdown(self) -> None:
  66. if hasattr(self, "forward_dag") and self.forward_dag is not None:
  67. self.forward_dag.teardown()
  68. import ray
  69. for worker in self.workers:
  70. ray.kill(worker)
  71. self.forward_dag = None
  72. def _configure_ray_workers_use_nsight(self,
  73. ray_remote_kwargs) -> Dict[str, Any]:
  74. # If nsight profiling is enabled, we need to set the profiling
  75. # configuration for the ray workers as runtime env.
  76. runtime_env = ray_remote_kwargs.setdefault("runtime_env", {})
  77. runtime_env.update({
  78. "nsight": {
  79. "t": "cuda,cudnn,cublas",
  80. "o": "'worker_process_%p'",
  81. "cuda-graph-trace": "node",
  82. }
  83. })
  84. return ray_remote_kwargs
  85. def _get_worker_wrapper_args(self) -> Dict[str, Any]:
  86. (worker_module_name, worker_class_name,
  87. worker_class_fn) = self._get_worker_module_and_class()
  88. return dict(
  89. worker_module_name=worker_module_name,
  90. worker_class_name=worker_class_name,
  91. worker_class_fn=worker_class_fn,
  92. trust_remote_code=self.model_config.trust_remote_code,
  93. )
  94. # child class could overwrite this to return actual env vars.
  95. def _get_env_vars_to_be_updated(self):
  96. return self._env_vars_for_all_workers
  97. def _init_workers_ray(self, placement_group: "PlacementGroup",
  98. **ray_remote_kwargs):
  99. if (self.parallel_config.tensor_parallel_size == 1
  100. and self.parallel_config.pipeline_parallel_size == 1):
  101. # For single GPU case, we use a ray worker with constrained memory.
  102. num_gpus = self.cache_config.gpu_memory_utilization
  103. else:
  104. # Otherwise, the ray workers are allocated with a full GPU.
  105. num_gpus = 1
  106. # The driver dummy worker does not actually use any resources.
  107. # It holds the resource for the driver worker.
  108. self.driver_dummy_worker: Optional[RayWorkerWrapper] = None
  109. # The remaining workers are the actual ray actors.
  110. self.workers: List[RayWorkerWrapper] = []
  111. # Used in ray compiled DAG: indexed first by PP rank,
  112. # and then TP rank. In other words, the inner list is
  113. # the TP group of workers for a PP rank.
  114. self.pp_tp_workers: List[List[RayWorkerWrapper]] = []
  115. if self.parallel_config.ray_workers_use_nsight:
  116. ray_remote_kwargs = self._configure_ray_workers_use_nsight(
  117. ray_remote_kwargs)
  118. logger.info(f"use_ray_spmd_worker: {self.use_ray_spmd_worker}")
  119. # Create the workers.
  120. driver_ip = get_ip()
  121. logger.info(f"driver_ip: {driver_ip}")
  122. worker_wrapper_kwargs = self._get_worker_wrapper_args()
  123. for bundle_id, bundle in enumerate(placement_group.bundle_specs):
  124. if not bundle.get("GPU", 0):
  125. continue
  126. scheduling_strategy = PlacementGroupSchedulingStrategy(
  127. placement_group=placement_group,
  128. placement_group_capture_child_tasks=True,
  129. placement_group_bundle_index=bundle_id,
  130. )
  131. worker = ray.remote(
  132. num_cpus=0,
  133. num_gpus=num_gpus,
  134. scheduling_strategy=scheduling_strategy,
  135. **ray_remote_kwargs,
  136. )(RayWorkerWrapper).remote(**worker_wrapper_kwargs)
  137. if self.use_ray_spmd_worker:
  138. self.workers.append(worker)
  139. else:
  140. worker_ip = ray.get(worker.get_node_ip.remote())
  141. if worker_ip == driver_ip and self.driver_dummy_worker is None:
  142. # If the worker is on the same node as the driver, we use it
  143. # as the resource holder for the driver process.
  144. self.driver_dummy_worker = worker
  145. self.driver_worker = RayWorkerWrapper(
  146. **worker_wrapper_kwargs)
  147. else:
  148. # Else, added to the list of workers.
  149. self.workers.append(worker)
  150. logger.debug(f"workers: {self.workers}")
  151. logger.debug(f"driver_dummy_worker: {self.driver_dummy_worker}")
  152. if not self.use_ray_spmd_worker and self.driver_dummy_worker is None:
  153. raise ValueError(
  154. "Ray does not allocate any GPUs on the driver node. Consider "
  155. "adjusting the Ray placement group or running the driver on a "
  156. "GPU node.")
  157. worker_ips = [
  158. ray.get(worker.get_node_ip.remote()) # type: ignore[attr-defined]
  159. for worker in self.workers
  160. ]
  161. ip_counts: Dict[str, int] = {}
  162. for ip in worker_ips:
  163. ip_counts[ip] = ip_counts.get(ip, 0) + 1
  164. def sort_by_driver_then_worker_ip(worker):
  165. """
  166. Sort the workers based on 3 properties:
  167. 1. If the worker is on the same node as the driver (vllm engine),
  168. it should be placed first.
  169. 2. Then, if the worker is on a node with fewer workers, it should
  170. be placed first.
  171. 3. Finally, if the work is on a node with smaller IP address, it
  172. should be placed first.
  173. """
  174. ip = ray.get(worker.get_node_ip.remote())
  175. return (ip != driver_ip, ip_counts[ip], ip)
  176. # After sorting, the workers on the same node will be
  177. # close to each other, and the workers on the driver
  178. # node will be placed first.
  179. self.workers = sorted(self.workers, key=sort_by_driver_then_worker_ip)
  180. # Get the set of GPU IDs used on each node.
  181. worker_node_and_gpu_ids = self._run_workers("get_node_and_gpu_ids",
  182. use_dummy_driver=True)
  183. node_workers = defaultdict(list) # node id -> list of worker ranks
  184. node_gpus = defaultdict(list) # node id -> list of gpu ids
  185. for i, (node_id, gpu_ids) in enumerate(worker_node_and_gpu_ids):
  186. node_workers[node_id].append(i)
  187. # `gpu_ids` can be a list of strings or integers.
  188. # convert them to integers for consistency.
  189. # NOTE: gpu_ids can be larger than 9 (e.g. 16 GPUs),
  190. # string sorting is not sufficient.
  191. gpu_ids = [int(x) for x in gpu_ids]
  192. node_gpus[node_id].extend(gpu_ids)
  193. for node_id, gpu_ids in node_gpus.items():
  194. node_gpus[node_id] = sorted(gpu_ids)
  195. APHRODITE_INSTANCE_ID = get_aphrodite_instance_id()
  196. # Set environment variables for the driver and workers.
  197. all_args_to_update_environment_variables = [({
  198. "CUDA_VISIBLE_DEVICES":
  199. ",".join(map(str, node_gpus[node_id])),
  200. "APHRODITE_INSTANCE_ID":
  201. APHRODITE_INSTANCE_ID,
  202. "APHRODITE_TRACE_FUNCTION":
  203. str(APHRODITE_TRACE_FUNCTION),
  204. }, ) for (node_id, _) in worker_node_and_gpu_ids]
  205. self._env_vars_for_all_workers = (
  206. all_args_to_update_environment_variables)
  207. self._run_workers("update_environment_variables",
  208. all_args=self._get_env_vars_to_be_updated())
  209. if len(node_gpus) == 1:
  210. # in single node case, we don't need to get the IP address.
  211. # the loopback address is sufficient
  212. # NOTE: a node may have several IP addresses, one for each
  213. # network interface. `get_ip()` might return any of them,
  214. # while they might not work for communication inside the node
  215. # if the network setup is complicated. Using the loopback address
  216. # solves this issue, as it always works for communication inside
  217. # the node.
  218. driver_ip = "127.0.0.1"
  219. distributed_init_method = get_distributed_init_method(
  220. driver_ip, get_open_port())
  221. # Initialize the actual workers inside worker wrapper.
  222. init_worker_all_kwargs = [
  223. self._get_worker_kwargs(
  224. local_rank=node_workers[node_id].index(rank),
  225. rank=rank,
  226. distributed_init_method=distributed_init_method,
  227. ) for rank, (node_id, _) in enumerate(worker_node_and_gpu_ids)
  228. ]
  229. self._run_workers("init_worker", all_kwargs=init_worker_all_kwargs)
  230. self._run_workers("init_device")
  231. self._run_workers("load_model",
  232. max_concurrent_workers=self.parallel_config.
  233. max_parallel_loading_workers)
  234. if self.use_ray_spmd_worker:
  235. for pp_rank in range(self.parallel_config.pipeline_parallel_size):
  236. self.pp_tp_workers.append([])
  237. for tp_rank in range(
  238. self.parallel_config.tensor_parallel_size):
  239. # PP=2, TP=4
  240. # pp_tp_workers = [[0, 1, 2, 3], [4, 5, 6, 7]]
  241. rank = (pp_rank * self.parallel_config.tensor_parallel_size
  242. ) + tp_rank
  243. assert len(self.pp_tp_workers[pp_rank]) == tp_rank
  244. assert pp_rank < len(self.pp_tp_workers)
  245. self.pp_tp_workers[pp_rank].append(self.workers[rank])
  246. # This is the list of workers that are rank 0 of each TP group EXCEPT
  247. # global rank 0. These are the workers that will broadcast to the
  248. # rest of the workers.
  249. self.tp_driver_workers: List[RayWorkerWrapper] = []
  250. # This is the list of workers that are not drivers and not the first
  251. # worker in a TP group. These are the workers that will be
  252. # broadcasted to.
  253. self.non_driver_workers: List[RayWorkerWrapper] = []
  254. # Enforce rank order for correct rank to return final output.
  255. for index, worker in enumerate(self.workers):
  256. # The driver worker is rank 0 and not in self.workers.
  257. rank = index + 1
  258. if rank % self.parallel_config.tensor_parallel_size == 0:
  259. self.tp_driver_workers.append(worker)
  260. else:
  261. self.non_driver_workers.append(worker)
  262. def _driver_execute_model(
  263. self, execute_model_req: Optional[ExecuteModelRequest]
  264. ) -> Optional[List[SamplerOutput]]:
  265. """Run execute_model in the driver worker.
  266. Passing None will cause the driver to stop the model execution
  267. loop running in each of the remote workers.
  268. """
  269. assert not self.use_ray_spmd_worker, (
  270. "driver_worker does not exist for APHRODITE_USE_RAY_SPMD_WORKER=1")
  271. return self.driver_worker.execute_method("execute_model",
  272. execute_model_req)
  273. def execute_model(
  274. self,
  275. execute_model_req: ExecuteModelRequest) -> List[SamplerOutput]:
  276. if not self.use_ray_spmd_worker:
  277. return super().execute_model(execute_model_req)
  278. if self.forward_dag is None:
  279. self.forward_dag = self._compiled_ray_dag(enable_asyncio=False)
  280. serialized_data = self.input_encoder.encode(execute_model_req)
  281. outputs = ray.get(self.forward_dag.execute(serialized_data))
  282. output = self.output_decoder.decode(outputs[0])
  283. return output
  284. def _run_workers(
  285. self,
  286. method: str,
  287. *args,
  288. async_run_tensor_parallel_workers_only: bool = False,
  289. all_args: Optional[List[Tuple[Any, ...]]] = None,
  290. all_kwargs: Optional[List[Dict[str, Any]]] = None,
  291. use_dummy_driver: bool = False,
  292. max_concurrent_workers: Optional[int] = None,
  293. **kwargs,
  294. ) -> Any:
  295. """Runs the given method on all workers. Can be used in the following
  296. ways:
  297. Args:
  298. - async_run_tensor_parallel_workers_only: If True the method will be
  299. run only in the remote TP workers, not the driver worker.
  300. It will also be run asynchronously and return a list of futures
  301. rather than blocking on the results.
  302. - args/kwargs: All workers share the same args/kwargs
  303. - all_args/all_kwargs: args/kwargs for each worker are specified
  304. individually
  305. """
  306. if self.use_ray_spmd_worker:
  307. assert not async_run_tensor_parallel_workers_only, (
  308. "async_run_tensor_parallel_workers_only is not supported for "
  309. "spmd mode.")
  310. if max_concurrent_workers:
  311. raise NotImplementedError(
  312. "max_concurrent_workers is not supported yet.")
  313. count = len(self.workers) if not \
  314. async_run_tensor_parallel_workers_only \
  315. else len(self.non_driver_workers)
  316. # If using SPMD worker, all workers are the same, so we should execute
  317. # the args on all workers. Otherwise, we skip the first worker's args
  318. # because those args will go to the driver worker.
  319. first_worker_args_index: int = 0 if self.use_ray_spmd_worker else 1
  320. all_worker_args = repeat(args, count) if all_args is None \
  321. else islice(all_args, first_worker_args_index, None)
  322. all_worker_kwargs = repeat(kwargs, count) if all_kwargs is None \
  323. else islice(all_kwargs, first_worker_args_index, None)
  324. # Start the ray workers first.
  325. ray_workers = self.workers
  326. if async_run_tensor_parallel_workers_only:
  327. ray_workers = self.non_driver_workers
  328. ray_worker_outputs = [
  329. worker.execute_method.remote(method, *worker_args, **worker_kwargs)
  330. for (worker, worker_args, worker_kwargs
  331. ) in zip(ray_workers, all_worker_args, all_worker_kwargs)
  332. ]
  333. if async_run_tensor_parallel_workers_only:
  334. # Just return futures
  335. return ray_worker_outputs
  336. driver_worker_output = []
  337. # In SPMD mode, the driver worker is the same as any other worker,
  338. # so we only explicitly execute on the driver worker if using a
  339. # non-SPMD worker class.
  340. if not self.use_ray_spmd_worker:
  341. driver_args = args if all_args is None else all_args[0]
  342. driver_kwargs = kwargs if all_kwargs is None else all_kwargs[0]
  343. # Start the driver worker after all the ray workers.
  344. if not use_dummy_driver:
  345. driver_worker_output = [
  346. self.driver_worker.execute_method(method, *driver_args,
  347. **driver_kwargs)
  348. ]
  349. else:
  350. assert self.driver_dummy_worker is not None
  351. driver_worker_output = [
  352. ray.get(
  353. self.driver_dummy_worker.execute_method.remote(
  354. method, *driver_args, **driver_kwargs))
  355. ]
  356. # Get the results of the ray workers.
  357. if self.workers:
  358. ray_worker_outputs = ray.get(ray_worker_outputs)
  359. return driver_worker_output + ray_worker_outputs
  360. def _wait_for_tasks_completion(self, parallel_worker_tasks: Any) -> None:
  361. """Wait for futures returned from _run_workers() with
  362. async_run_remote_workers_only to complete."""
  363. ray.get(parallel_worker_tasks)
  364. def _compiled_ray_dag(self, enable_asyncio: bool):
  365. import pkg_resources
  366. from packaging import version
  367. required_version = version.parse("2.32")
  368. current_version = version.parse(
  369. pkg_resources.get_distribution("ray").version)
  370. if current_version < required_version:
  371. raise ValueError(f"Ray version {required_version} or greater is "
  372. f"required, but found {current_version}")
  373. assert self.parallel_config.use_ray
  374. from ray.dag import InputNode, MultiOutputNode
  375. from ray.experimental.channel.torch_tensor_type import TorchTensorType
  376. logger.info(f"APHRODITE_USE_RAY_COMPILED_DAG_NCCL_CHANNEL = "
  377. f"{APHRODITE_USE_RAY_COMPILED_DAG_NCCL_CHANNEL}")
  378. with InputNode() as input_data:
  379. # Example DAG: PP=2, TP=4
  380. # (ExecuteModelReq, None) -> 0 -> (ExecuteModelReq, IntermediateOutput) -> 4 -> SamplerOutput # noqa: E501
  381. # -> 1 -> (ExecuteModelReq, IntermediateOutput) -> 5 -> SamplerOutput # noqa: E501
  382. # -> 2 -> (ExecuteModelReq, IntermediateOutput) -> 6 -> SamplerOutput # noqa: E501
  383. # -> 3 -> (ExecuteModelReq, IntermediateOutput) -> 7 -> SamplerOutput # noqa: E501
  384. # All workers in the first TP group will take in the
  385. # ExecuteModelRequest as input.
  386. outputs = [input_data for _ in self.pp_tp_workers[0]]
  387. for pp_rank, tp_group in enumerate(self.pp_tp_workers):
  388. # Each PP worker takes in the output of the previous PP worker,
  389. # and the TP group executes in SPMD fashion.
  390. outputs = [
  391. worker.execute_model_spmd.
  392. bind( # type: ignore[attr-defined]
  393. outputs[i]) for i, worker in enumerate(tp_group)
  394. ]
  395. last_pp_rank = len(self.pp_tp_workers) - 1
  396. if pp_rank < last_pp_rank:
  397. # Specify how intermediate tensors should be passed
  398. # between pp stages, no need to specify for the last
  399. # pp stage.
  400. transport = "nccl" \
  401. if APHRODITE_USE_RAY_COMPILED_DAG_NCCL_CHANNEL \
  402. else "auto"
  403. outputs = [
  404. output.with_type_hint(
  405. TorchTensorType(transport=transport))
  406. for output in outputs
  407. ]
  408. forward_dag = MultiOutputNode(outputs)
  409. return forward_dag.experimental_compile(enable_asyncio=enable_asyncio)
  410. def __del__(self):
  411. self.shutdown()
  412. class RayGPUExecutorAsync(RayGPUExecutor, DistributedGPUExecutorAsync):
  413. def __init__(self, *args, **kwargs):
  414. super().__init__(*args, **kwargs)
  415. self.pp_locks: Optional[List[asyncio.Lock]] = None
  416. self.use_ray_spmd_worker = APHRODITE_USE_RAY_SPMD_WORKER
  417. if not self.use_ray_compiled_dag:
  418. self.driver_exec_method = make_async(
  419. self.driver_worker.execute_method)
  420. async def execute_model_async(
  421. self,
  422. execute_model_req: ExecuteModelRequest) -> List[SamplerOutput]:
  423. if not self.use_ray_spmd_worker:
  424. return await super().execute_model_async(execute_model_req)
  425. if self.forward_dag is None:
  426. self.forward_dag = self._compiled_ray_dag(enable_asyncio=True)
  427. serialized_data = self.input_encoder.encode(execute_model_req)
  428. dag_future = await self.forward_dag.execute_async(serialized_data)
  429. outputs = await dag_future
  430. return self.output_decoder.decode(outputs[0])
  431. async def _driver_execute_model_async(
  432. self,
  433. execute_model_req: Optional[ExecuteModelRequest] = None
  434. ) -> List[SamplerOutput]:
  435. assert not self.use_ray_spmd_worker, (
  436. "driver_worker does not exist for APHRODITE_USE_RAY_SPMD_WORKER=1")
  437. if not self.tp_driver_workers:
  438. return await self.driver_exec_method("execute_model",
  439. execute_model_req)
  440. if self.pp_locks is None:
  441. # This locks each pipeline parallel stage so multiple virtual
  442. # engines can't execute on the same stage at the same time
  443. # We create the locks here to avoid creating them in the constructor
  444. # which uses a different asyncio loop.
  445. self.pp_locks = [
  446. asyncio.Lock()
  447. for _ in range(self.parallel_config.pipeline_parallel_size)
  448. ]
  449. tasks = [
  450. asyncio.create_task(
  451. _run_task_with_lock(self.driver_exec_method, self.pp_locks[0],
  452. "execute_model", execute_model_req))
  453. ]
  454. for pp_rank, driver_worker in enumerate(self.tp_driver_workers,
  455. start=1):
  456. tasks.append(
  457. asyncio.create_task(
  458. _run_task_with_lock(driver_worker.execute_method.remote,
  459. self.pp_locks[pp_rank],
  460. "execute_model", execute_model_req)))
  461. results = await asyncio.gather(*tasks)
  462. # Only the last PP stage has the final results.
  463. return results[-1]
  464. async def _start_worker_execution_loop(self):
  465. assert not self.use_ray_spmd_worker, (
  466. "worker loop is disabled for APHRODITE_USE_RAY_SPMD_WORKER=1")
  467. coros = [
  468. worker.execute_method.remote("start_worker_execution_loop")
  469. for worker in self.non_driver_workers
  470. ]
  471. return await asyncio.gather(*coros)
  472. def __del__(self):
  473. self.shutdown()