ray_gpu_executor.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  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. if self.speculative_config is not None:
  87. worker_module_name = "aphrodite.spec_decode.spec_decode_worker"
  88. worker_class_name = "create_spec_worker"
  89. else:
  90. worker_module_name = "aphrodite.task_handler.worker"
  91. worker_class_name = "Worker"
  92. return dict(
  93. worker_module_name=worker_module_name,
  94. worker_class_name=worker_class_name,
  95. trust_remote_code=self.model_config.trust_remote_code,
  96. )
  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._run_workers("update_environment_variables",
  206. all_args=all_args_to_update_environment_variables)
  207. if len(node_gpus) == 1:
  208. # in single node case, we don't need to get the IP address.
  209. # the loopback address is sufficient
  210. # NOTE: a node may have several IP addresses, one for each
  211. # network interface. `get_ip()` might return any of them,
  212. # while they might not work for communication inside the node
  213. # if the network setup is complicated. Using the loopback address
  214. # solves this issue, as it always works for communication inside
  215. # the node.
  216. driver_ip = "127.0.0.1"
  217. distributed_init_method = get_distributed_init_method(
  218. driver_ip, get_open_port())
  219. # Initialize the actual workers inside worker wrapper.
  220. init_worker_all_kwargs = [
  221. self._get_worker_kwargs(
  222. local_rank=node_workers[node_id].index(rank),
  223. rank=rank,
  224. distributed_init_method=distributed_init_method,
  225. ) for rank, (node_id, _) in enumerate(worker_node_and_gpu_ids)
  226. ]
  227. self._run_workers("init_worker", all_kwargs=init_worker_all_kwargs)
  228. self._run_workers("init_device")
  229. self._run_workers("load_model",
  230. max_concurrent_workers=self.parallel_config.
  231. max_parallel_loading_workers)
  232. if self.use_ray_spmd_worker:
  233. for pp_rank in range(self.parallel_config.pipeline_parallel_size):
  234. self.pp_tp_workers.append([])
  235. for tp_rank in range(
  236. self.parallel_config.tensor_parallel_size):
  237. # PP=2, TP=4
  238. # pp_tp_workers = [[0, 1, 2, 3], [4, 5, 6, 7]]
  239. rank = (pp_rank * self.parallel_config.tensor_parallel_size
  240. ) + tp_rank
  241. assert len(self.pp_tp_workers[pp_rank]) == tp_rank
  242. assert pp_rank < len(self.pp_tp_workers)
  243. self.pp_tp_workers[pp_rank].append(self.workers[rank])
  244. # This is the list of workers that are rank 0 of each TP group EXCEPT
  245. # global rank 0. These are the workers that will broadcast to the
  246. # rest of the workers.
  247. self.tp_driver_workers: List[RayWorkerWrapper] = []
  248. # This is the list of workers that are not drivers and not the first
  249. # worker in a TP group. These are the workers that will be
  250. # broadcasted to.
  251. self.non_driver_workers: List[RayWorkerWrapper] = []
  252. # Enforce rank order for correct rank to return final output.
  253. for index, worker in enumerate(self.workers):
  254. # The driver worker is rank 0 and not in self.workers.
  255. rank = index + 1
  256. if rank % self.parallel_config.tensor_parallel_size == 0:
  257. self.tp_driver_workers.append(worker)
  258. else:
  259. self.non_driver_workers.append(worker)
  260. def _driver_execute_model(
  261. self, execute_model_req: Optional[ExecuteModelRequest]
  262. ) -> Optional[List[SamplerOutput]]:
  263. """Run execute_model in the driver worker.
  264. Passing None will cause the driver to stop the model execution
  265. loop running in each of the remote workers.
  266. """
  267. assert not self.use_ray_spmd_worker, (
  268. "driver_worker does not exist for APHRODITE_USE_RAY_SPMD_WORKER=1")
  269. return self.driver_worker.execute_method("execute_model",
  270. execute_model_req)
  271. def execute_model(
  272. self,
  273. execute_model_req: ExecuteModelRequest) -> List[SamplerOutput]:
  274. if not self.use_ray_spmd_worker:
  275. return super().execute_model(execute_model_req)
  276. if self.forward_dag is None:
  277. self.forward_dag = self._compiled_ray_dag(enable_asyncio=False)
  278. serialized_data = self.input_encoder.encode(execute_model_req)
  279. outputs = ray.get(self.forward_dag.execute(serialized_data))
  280. output = self.output_decoder.decode(outputs[0])
  281. return output
  282. def _run_workers(
  283. self,
  284. method: str,
  285. *args,
  286. async_run_tensor_parallel_workers_only: bool = False,
  287. all_args: Optional[List[Tuple[Any, ...]]] = None,
  288. all_kwargs: Optional[List[Dict[str, Any]]] = None,
  289. use_dummy_driver: bool = False,
  290. max_concurrent_workers: Optional[int] = None,
  291. **kwargs,
  292. ) -> Any:
  293. """Runs the given method on all workers. Can be used in the following
  294. ways:
  295. Args:
  296. - async_run_tensor_parallel_workers_only: If True the method will be
  297. run only in the remote TP workers, not the driver worker.
  298. It will also be run asynchronously and return a list of futures
  299. rather than blocking on the results.
  300. - args/kwargs: All workers share the same args/kwargs
  301. - all_args/all_kwargs: args/kwargs for each worker are specified
  302. individually
  303. """
  304. if self.use_ray_spmd_worker:
  305. assert not async_run_tensor_parallel_workers_only, (
  306. "async_run_tensor_parallel_workers_only is not supported for "
  307. "spmd mode.")
  308. if max_concurrent_workers:
  309. raise NotImplementedError(
  310. "max_concurrent_workers is not supported yet.")
  311. count = len(self.workers) if not \
  312. async_run_tensor_parallel_workers_only \
  313. else len(self.non_driver_workers)
  314. # If using SPMD worker, all workers are the same, so we should execute
  315. # the args on all workers. Otherwise, we skip the first worker's args
  316. # because those args will go to the driver worker.
  317. first_worker_args_index: int = 0 if self.use_ray_spmd_worker else 1
  318. all_worker_args = repeat(args, count) if all_args is None \
  319. else islice(all_args, first_worker_args_index, None)
  320. all_worker_kwargs = repeat(kwargs, count) if all_kwargs is None \
  321. else islice(all_kwargs, first_worker_args_index, None)
  322. # Start the ray workers first.
  323. ray_workers = self.workers
  324. if async_run_tensor_parallel_workers_only:
  325. ray_workers = self.non_driver_workers
  326. ray_worker_outputs = [
  327. worker.execute_method.remote(method, *worker_args, **worker_kwargs)
  328. for (worker, worker_args, worker_kwargs
  329. ) in zip(ray_workers, all_worker_args, all_worker_kwargs)
  330. ]
  331. if async_run_tensor_parallel_workers_only:
  332. # Just return futures
  333. return ray_worker_outputs
  334. driver_worker_output = []
  335. # In SPMD mode, the driver worker is the same as any other worker,
  336. # so we only explicitly execute on the driver worker if using a
  337. # non-SPMD worker class.
  338. if not self.use_ray_spmd_worker:
  339. driver_args = args if all_args is None else all_args[0]
  340. driver_kwargs = kwargs if all_kwargs is None else all_kwargs[0]
  341. # Start the driver worker after all the ray workers.
  342. if not use_dummy_driver:
  343. driver_worker_output = [
  344. self.driver_worker.execute_method(method, *driver_args,
  345. **driver_kwargs)
  346. ]
  347. else:
  348. assert self.driver_dummy_worker is not None
  349. driver_worker_output = [
  350. ray.get(
  351. self.driver_dummy_worker.execute_method.remote(
  352. method, *driver_args, **driver_kwargs))
  353. ]
  354. # Get the results of the ray workers.
  355. if self.workers:
  356. ray_worker_outputs = ray.get(ray_worker_outputs)
  357. return driver_worker_output + ray_worker_outputs
  358. def _wait_for_tasks_completion(self, parallel_worker_tasks: Any) -> None:
  359. """Wait for futures returned from _run_workers() with
  360. async_run_remote_workers_only to complete."""
  361. ray.get(parallel_worker_tasks)
  362. def _compiled_ray_dag(self, enable_asyncio: bool):
  363. import pkg_resources
  364. from packaging import version
  365. required_version = version.parse("2.32")
  366. current_version = version.parse(
  367. pkg_resources.get_distribution("ray").version)
  368. if current_version < required_version:
  369. raise ValueError(f"Ray version {required_version} or greater is "
  370. f"required, but found {current_version}")
  371. assert self.parallel_config.use_ray
  372. from ray.dag import InputNode, MultiOutputNode
  373. from ray.experimental.channel.torch_tensor_type import TorchTensorType
  374. logger.info(f"APHRODITE_USE_RAY_COMPILED_DAG_NCCL_CHANNEL = "
  375. f"{APHRODITE_USE_RAY_COMPILED_DAG_NCCL_CHANNEL}")
  376. with InputNode() as input_data:
  377. # Example DAG: PP=2, TP=4
  378. # (ExecuteModelReq, None) -> 0 -> (ExecuteModelReq, IntermediateOutput) -> 4 -> SamplerOutput # noqa: E501
  379. # -> 1 -> (ExecuteModelReq, IntermediateOutput) -> 5 -> SamplerOutput # noqa: E501
  380. # -> 2 -> (ExecuteModelReq, IntermediateOutput) -> 6 -> SamplerOutput # noqa: E501
  381. # -> 3 -> (ExecuteModelReq, IntermediateOutput) -> 7 -> SamplerOutput # noqa: E501
  382. # All workers in the first TP group will take in the
  383. # ExecuteModelRequest as input.
  384. outputs = [input_data for _ in self.pp_tp_workers[0]]
  385. for pp_rank, tp_group in enumerate(self.pp_tp_workers):
  386. # Each PP worker takes in the output of the previous PP worker,
  387. # and the TP group executes in SPMD fashion.
  388. outputs = [
  389. worker.execute_model_spmd.
  390. bind( # type: ignore[attr-defined]
  391. outputs[i]) for i, worker in enumerate(tp_group)
  392. ]
  393. last_pp_rank = len(self.pp_tp_workers) - 1
  394. if pp_rank < last_pp_rank:
  395. # Specify how intermediate tensors should be passed
  396. # between pp stages, no need to specify for the last
  397. # pp stage.
  398. transport = "nccl" \
  399. if APHRODITE_USE_RAY_COMPILED_DAG_NCCL_CHANNEL \
  400. else "auto"
  401. outputs = [
  402. output.with_type_hint(
  403. TorchTensorType(transport=transport))
  404. for output in outputs
  405. ]
  406. forward_dag = MultiOutputNode(outputs)
  407. return forward_dag.experimental_compile(enable_asyncio=enable_asyncio)
  408. def __del__(self):
  409. self.shutdown()
  410. class RayGPUExecutorAsync(RayGPUExecutor, DistributedGPUExecutorAsync):
  411. def __init__(self, *args, **kwargs):
  412. super().__init__(*args, **kwargs)
  413. self.pp_locks: Optional[List[asyncio.Lock]] = None
  414. self.use_ray_spmd_worker = APHRODITE_USE_RAY_SPMD_WORKER
  415. if not self.use_ray_compiled_dag:
  416. self.driver_exec_method = make_async(
  417. self.driver_worker.execute_method)
  418. async def execute_model_async(
  419. self,
  420. execute_model_req: ExecuteModelRequest) -> List[SamplerOutput]:
  421. if not self.use_ray_spmd_worker:
  422. return await super().execute_model_async(execute_model_req)
  423. if self.forward_dag is None:
  424. self.forward_dag = self._compiled_ray_dag(enable_asyncio=True)
  425. serialized_data = self.input_encoder.encode(execute_model_req)
  426. dag_future = await self.forward_dag.execute_async(serialized_data)
  427. outputs = await dag_future
  428. return self.output_decoder.decode(outputs[0])
  429. async def _driver_execute_model_async(
  430. self,
  431. execute_model_req: Optional[ExecuteModelRequest] = None
  432. ) -> List[SamplerOutput]:
  433. assert not self.use_ray_spmd_worker, (
  434. "driver_worker does not exist for APHRODITE_USE_RAY_SPMD_WORKER=1")
  435. if not self.tp_driver_workers:
  436. return await self.driver_exec_method("execute_model",
  437. execute_model_req)
  438. if self.pp_locks is None:
  439. # This locks each pipeline parallel stage so multiple virtual
  440. # engines can't execute on the same stage at the same time
  441. # We create the locks here to avoid creating them in the constructor
  442. # which uses a different asyncio loop.
  443. self.pp_locks = [
  444. asyncio.Lock()
  445. for _ in range(self.parallel_config.pipeline_parallel_size)
  446. ]
  447. tasks = [
  448. asyncio.create_task(
  449. _run_task_with_lock(self.driver_exec_method, self.pp_locks[0],
  450. "execute_model", execute_model_req))
  451. ]
  452. for pp_rank, driver_worker in enumerate(self.tp_driver_workers,
  453. start=1):
  454. tasks.append(
  455. asyncio.create_task(
  456. _run_task_with_lock(driver_worker.execute_method.remote,
  457. self.pp_locks[pp_rank],
  458. "execute_model", execute_model_req)))
  459. results = await asyncio.gather(*tasks)
  460. # Only the last PP stage has the final results.
  461. return results[-1]
  462. async def _start_worker_execution_loop(self):
  463. assert not self.use_ray_spmd_worker, (
  464. "worker loop is disabled for APHRODITE_USE_RAY_SPMD_WORKER=1")
  465. coros = [
  466. worker.execute_method.remote("start_worker_execution_loop")
  467. for worker in self.non_driver_workers
  468. ]
  469. return await asyncio.gather(*coros)
  470. def __del__(self):
  471. self.shutdown()