distributed_gpu_executor.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. import asyncio
  2. from abc import abstractmethod
  3. from typing import Any, Awaitable, Dict, List, Optional, Set, Tuple, Union
  4. from loguru import logger
  5. from aphrodite.common.sequence import ExecuteModelRequest, SamplerOutput
  6. from aphrodite.executor.executor_base import ExecutorAsyncBase
  7. from aphrodite.executor.gpu_executor import GPUExecutor
  8. from aphrodite.lora.request import LoRARequest
  9. class DistributedGPUExecutor(GPUExecutor):
  10. """Abstract superclass of multi-GPU executor implementations."""
  11. def __init__(self, *args, **kwargs):
  12. # This is non-None when the execute model loop is running
  13. # in the parallel workers. It's a coroutine in the AsyncLLMEngine case.
  14. self.parallel_worker_tasks: Optional[Union[Any, Awaitable[Any]]] = None
  15. # Updated by implementations that require additional args to be passed
  16. # to the _run_workers execute_model call
  17. self.extra_execute_model_run_workers_kwargs: Dict[str, Any] = {}
  18. super().__init__(*args, **kwargs)
  19. def determine_num_available_blocks(self) -> Tuple[int, int]:
  20. """Determine the number of available KV blocks.
  21. This invokes `determine_num_available_blocks` on each worker and takes
  22. the min of the results, guaranteeing that the selected cache sizes are
  23. compatible with all workers.
  24. Returns:
  25. - tuple[num_gpu_blocks, num_cpu_blocks]
  26. """
  27. # Get the maximum number of blocks that can be allocated on GPU and CPU.
  28. num_blocks = self._run_workers("determine_num_available_blocks", )
  29. # Since we use a shared centralized controller, we take the minimum
  30. # number of blocks across all workers to make sure all the memory
  31. # operators can be applied to all workers.
  32. num_gpu_blocks = min(b[0] for b in num_blocks)
  33. num_cpu_blocks = min(b[1] for b in num_blocks)
  34. return num_gpu_blocks, num_cpu_blocks
  35. def initialize_cache(self, num_gpu_blocks: int,
  36. num_cpu_blocks: int) -> None:
  37. """Initialize the KV cache in all workers.
  38. """
  39. # NOTE: We log here to avoid multiple logs when number of workers is
  40. # greater than one. We could log in the engine, but not all executors
  41. # have GPUs.
  42. logger.info(f"# GPU blocks: {num_gpu_blocks}, "
  43. f"# CPU blocks: {num_cpu_blocks}")
  44. logger.info(
  45. f"Minimum concurrency: {num_gpu_blocks * self.cache_config.block_size / self.scheduler_config.max_model_len:.2f}x" # noqa: E501
  46. )
  47. self.cache_config.num_gpu_blocks = num_gpu_blocks
  48. self.cache_config.num_cpu_blocks = num_cpu_blocks
  49. self._run_workers("initialize_cache",
  50. num_gpu_blocks=num_gpu_blocks,
  51. num_cpu_blocks=num_cpu_blocks)
  52. def execute_model(
  53. self,
  54. execute_model_req: ExecuteModelRequest) -> List[SamplerOutput]:
  55. if self.parallel_worker_tasks is None:
  56. self.parallel_worker_tasks = self._run_workers(
  57. "start_worker_execution_loop",
  58. async_run_tensor_parallel_workers_only=True,
  59. **self.extra_execute_model_run_workers_kwargs)
  60. # Only the driver worker returns the sampling results.
  61. driver_outputs = self._driver_execute_model(execute_model_req)
  62. assert driver_outputs is not None
  63. return driver_outputs
  64. def stop_remote_worker_execution_loop(self) -> None:
  65. if self.parallel_worker_tasks is None:
  66. return
  67. self._driver_execute_model(execute_model_req=None)
  68. parallel_worker_tasks = self.parallel_worker_tasks
  69. self.parallel_worker_tasks = None
  70. # Ensure that workers exit model loop cleanly
  71. # (this will raise otherwise)
  72. self._wait_for_tasks_completion(parallel_worker_tasks)
  73. def add_lora(self, lora_request: LoRARequest) -> bool:
  74. assert lora_request.lora_int_id > 0, "lora_id must be greater than 0."
  75. return self._run_workers(
  76. "add_lora",
  77. lora_request=lora_request,
  78. )
  79. def remove_lora(self, lora_id: int) -> bool:
  80. assert lora_id > 0, "lora_id must be greater than 0."
  81. return self._run_workers(
  82. "remove_lora",
  83. lora_id=lora_id,
  84. )
  85. def list_loras(self) -> Set[int]:
  86. return self._run_workers("list_loras")
  87. def pin_lora(self, lora_id: int) -> bool:
  88. assert lora_id > 0, "lora_id must be greater than 0."
  89. return self._run_workers(
  90. "pin_lora",
  91. lora_id=lora_id,
  92. )
  93. def save_sharded_state(
  94. self,
  95. path: str,
  96. pattern: Optional[str] = None,
  97. max_size: Optional[int] = None,
  98. ) -> None:
  99. self._run_workers("save_sharded_state",
  100. path=path,
  101. pattern=pattern,
  102. max_size=max_size)
  103. @abstractmethod
  104. def _driver_execute_model(
  105. self, execute_model_req: Optional[ExecuteModelRequest]
  106. ) -> Optional[List[SamplerOutput]]:
  107. """Run execute_model in the driver worker.
  108. Passing None will cause the driver to stop the model execution loop
  109. running in each of the remote workers. In this case, this method
  110. returns None. Otherwise, this method returns the model output.
  111. """
  112. raise NotImplementedError
  113. @abstractmethod
  114. def _run_workers(
  115. self,
  116. method: str,
  117. *args,
  118. async_run_tensor_parallel_workers_only: bool = False,
  119. max_concurrent_workers: Optional[int] = None,
  120. **kwargs,
  121. ) -> Any:
  122. """Runs the given method on all workers.
  123. Args:
  124. async_run_tensor_parallel_workers_only: If True the method will be
  125. run only in the remote TP workers, not the driver worker.
  126. It will also be run asynchronously and return a list of futures
  127. rather than blocking on the results.
  128. """
  129. raise NotImplementedError
  130. @abstractmethod
  131. def _wait_for_tasks_completion(self, parallel_worker_tasks: Any) -> None:
  132. """Wait for futures returned from _run_workers() with
  133. async_run_remote_workers_only to complete."""
  134. raise NotImplementedError
  135. class DistributedGPUExecutorAsync(DistributedGPUExecutor, ExecutorAsyncBase):
  136. async def execute_model_async(
  137. self,
  138. execute_model_req: ExecuteModelRequest) -> List[SamplerOutput]:
  139. if self.parallel_worker_tasks is None:
  140. # Start model execution loop running in the parallel workers
  141. self.parallel_worker_tasks = asyncio.create_task(
  142. self._start_worker_execution_loop())
  143. # Only the driver worker returns the sampling results.
  144. return await self._driver_execute_model_async(execute_model_req)
  145. async def stop_remote_worker_execution_loop_async(self) -> None:
  146. if self.parallel_worker_tasks is None:
  147. return
  148. await self._driver_execute_model_async()
  149. parallel_worker_tasks = self.parallel_worker_tasks
  150. self.parallel_worker_tasks = None
  151. # Ensure that workers exit model loop cleanly
  152. # (this will raise otherwise)
  153. await parallel_worker_tasks
  154. @abstractmethod
  155. async def _driver_execute_model_async(
  156. self,
  157. execute_model_req: Optional[ExecuteModelRequest] = None
  158. ) -> List[SamplerOutput]:
  159. """Execute the model asynchronously in the driver worker.
  160. Passing None will cause the driver to stop the model execution
  161. loop running in each of the remote workers.
  162. """
  163. raise NotImplementedError
  164. @abstractmethod
  165. async def _start_worker_execution_loop(self):
  166. """Run execution loop on all workers. It guarantees all workers run
  167. the loop or None of them is running the loop. Loop can be stopped by
  168. `stop_remote_worker_execution_loop`.
  169. The API is idempotent (guarantee only 1 loop run at any moment)."""
  170. raise NotImplementedError