ray_gpu_executor.py 25 KB

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