multiproc_gpu_executor.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. import asyncio
  2. import os
  3. from functools import partial
  4. from typing import Any, List, Optional
  5. import torch
  6. from loguru import logger
  7. from aphrodite.common.sequence import ExecuteModelRequest
  8. from aphrodite.common.utils import (_run_task_with_lock,
  9. cuda_device_count_stateless,
  10. get_aphrodite_instance_id,
  11. get_distributed_init_method, get_open_port,
  12. make_async, update_environment_variables)
  13. from aphrodite.executor.distributed_gpu_executor import ( # yapf: disable
  14. DistributedGPUExecutor, DistributedGPUExecutorAsync)
  15. from aphrodite.executor.gpu_executor import create_worker
  16. from aphrodite.executor.multiproc_worker_utils import (ProcessWorkerWrapper,
  17. ResultHandler,
  18. WorkerMonitor)
  19. from aphrodite.modeling.layers.sampler import SamplerOutput
  20. from aphrodite.triton_utils import maybe_set_triton_cache_manager
  21. class MultiprocessingGPUExecutor(DistributedGPUExecutor):
  22. """Python multiprocessing-based multi-GPU executor"""
  23. uses_ray: bool = False
  24. def _init_executor(self) -> None:
  25. self._check_executor_parameters()
  26. # Create the parallel GPU workers.
  27. world_size = self.parallel_config.world_size
  28. tensor_parallel_size = self.parallel_config.tensor_parallel_size
  29. # Ensure that APHRODITE_INSTANCE_ID is set, to be inherited by workers
  30. os.environ["APHRODITE_INSTANCE_ID"] = get_aphrodite_instance_id()
  31. # Disable torch async compiling which won't work with daemonic processes
  32. os.environ["TORCHINDUCTOR_COMPILE_THREADS"] = "1"
  33. # Configure thread parallelism if OMP_NUM_THREADS isn't set
  34. #
  35. # Helps to avoid CPU contention. The default of spawning a thread per
  36. # core combined with multiprocessing for each GPU can have a negative
  37. # impact on performance. The contention is amplified when running in a
  38. # container where CPU limits can cause throttling.
  39. default_omp_num_threads = 1
  40. if "OMP_NUM_THREADS" not in os.environ and (
  41. current_parallelism :=
  42. torch.get_num_threads()) > default_omp_num_threads:
  43. logger.warning(
  44. f"Reducing Torch parallelism from {current_parallelism} "
  45. f"threads to {default_omp_num_threads} to avoid "
  46. "unnecessary CPU contention. Set OMP_NUM_THREADS in the "
  47. "external environment to tune this value as needed.")
  48. os.environ["OMP_NUM_THREADS"] = str(default_omp_num_threads)
  49. torch.set_num_threads(default_omp_num_threads)
  50. if world_size > 1:
  51. maybe_set_triton_cache_manager()
  52. # Multiprocessing-based executor does not support multi-node setting.
  53. # Since it only works for single node, we can use the loopback address
  54. # 127.0.0.1 for communication.
  55. distributed_init_method = get_distributed_init_method(
  56. "127.0.0.1", get_open_port())
  57. self.workers: List[ProcessWorkerWrapper] = []
  58. # This is the list of workers that are rank 0 of each TP group EXCEPT
  59. # global rank 0. These are the workers that will broadcast to the
  60. # rest of the workers.
  61. self.tp_driver_workers: List[ProcessWorkerWrapper] = []
  62. # This is the list of workers that are not drivers and not the first
  63. # worker in a TP group. These are the workers that will be
  64. # broadcasted to.
  65. self.non_driver_workers: List[ProcessWorkerWrapper] = []
  66. if world_size == 1:
  67. self.worker_monitor = None
  68. else:
  69. result_handler = ResultHandler()
  70. for rank in range(1, world_size):
  71. worker = ProcessWorkerWrapper(
  72. result_handler,
  73. partial(
  74. create_worker,
  75. **self._get_create_worker_kwargs(
  76. rank=rank,
  77. local_rank=rank,
  78. distributed_init_method=distributed_init_method,
  79. )))
  80. self.workers.append(worker)
  81. if rank % tensor_parallel_size == 0:
  82. self.tp_driver_workers.append(worker)
  83. else:
  84. self.non_driver_workers.append(worker)
  85. self.worker_monitor = WorkerMonitor(self.workers, result_handler)
  86. result_handler.start()
  87. self.worker_monitor.start()
  88. # Set up signal handlers to shutdown the executor cleanly
  89. # sometimes gc does not work well
  90. self.driver_worker = self._create_worker(
  91. distributed_init_method=distributed_init_method)
  92. self._run_workers("init_device")
  93. self._run_workers("load_model",
  94. max_concurrent_workers=self.parallel_config.
  95. max_parallel_loading_workers)
  96. def _check_executor_parameters(self):
  97. world_size = self.parallel_config.world_size
  98. tensor_parallel_size = self.parallel_config.tensor_parallel_size
  99. # Set CUDA_VISIBLE_DEVICES for the driver, inherited by workers
  100. if "CUDA_VISIBLE_DEVICES" not in os.environ:
  101. update_environment_variables({
  102. "CUDA_VISIBLE_DEVICES": (",".join(map(str, range(world_size))))
  103. })
  104. cuda_device_count = cuda_device_count_stateless()
  105. # Use confusing message for more common TP-only case.
  106. assert tensor_parallel_size <= cuda_device_count, (
  107. f"please set tensor_parallel_size ({tensor_parallel_size}) "
  108. f"to less than max local gpu count ({cuda_device_count})")
  109. assert world_size <= cuda_device_count, (
  110. f"please ensure that world_size ({world_size}) "
  111. f"is less than than max local gpu count ({cuda_device_count})")
  112. def shutdown(self):
  113. if (worker_monitor := getattr(self, "worker_monitor",
  114. None)) is not None:
  115. worker_monitor.close()
  116. def _driver_execute_model(
  117. self, execute_model_req: Optional[ExecuteModelRequest]
  118. ) -> Optional[List[SamplerOutput]]:
  119. """Run execute_model in the driver worker.
  120. Passing None will cause the driver to stop the model execution
  121. loop running in each of the remote workers.
  122. """
  123. return self.driver_worker.execute_model(execute_model_req)
  124. def _run_workers(
  125. self,
  126. method: str,
  127. *args,
  128. async_run_tensor_parallel_workers_only: bool = False,
  129. max_concurrent_workers: Optional[int] = None,
  130. **kwargs,
  131. ) -> Any:
  132. """Runs the given method on all workers.
  133. Args:
  134. async_run_tensor_parallel_workers_only: If True the method will be
  135. run only in the remote TP workers, not the driver worker.
  136. It will also be run asynchronously and return a list of futures
  137. rather than blocking on the results.
  138. """
  139. if max_concurrent_workers:
  140. raise NotImplementedError(
  141. "max_concurrent_workers is not supported yet.")
  142. if async_run_tensor_parallel_workers_only:
  143. # Run only non-driver workers and just return futures.
  144. return [
  145. worker.execute_method(method, *args, **kwargs)
  146. for worker in self.non_driver_workers
  147. ]
  148. # Start all remote workers first.
  149. worker_outputs = [
  150. worker.execute_method(method, *args, **kwargs)
  151. for worker in self.workers
  152. ]
  153. driver_worker_method = getattr(self.driver_worker, method)
  154. driver_worker_output = driver_worker_method(*args, **kwargs)
  155. # Get the results of the workers.
  156. return [driver_worker_output
  157. ] + [output.get() for output in worker_outputs]
  158. def check_health(self) -> None:
  159. """Raises an error if engine is unhealthy."""
  160. if self.worker_monitor is not None and not self.worker_monitor.is_alive(
  161. ):
  162. raise RuntimeError("Worker processes are not running")
  163. def _wait_for_tasks_completion(self, parallel_worker_tasks: Any) -> None:
  164. """Wait for futures returned from _run_workers() with
  165. async_run_remote_workers_only to complete."""
  166. for result in parallel_worker_tasks:
  167. result.get()
  168. class MultiprocessingGPUExecutorAsync(MultiprocessingGPUExecutor,
  169. DistributedGPUExecutorAsync):
  170. def __init__(self, *args, **kwargs):
  171. super().__init__(*args, **kwargs)
  172. self.driver_exec_model = make_async(self.driver_worker.execute_model)
  173. self.pp_locks: Optional[List[asyncio.Lock]] = None
  174. async def _driver_execute_model_async(
  175. self,
  176. execute_model_req: Optional[ExecuteModelRequest] = None
  177. ) -> List[SamplerOutput]:
  178. if not self.tp_driver_workers:
  179. return await self.driver_exec_model(execute_model_req)
  180. if self.pp_locks is None:
  181. # This locks each pipeline parallel stage so multiple virtual
  182. # engines can't execute on the same stage at the same time
  183. # We create the locks here to avoid creating them in the constructor
  184. # which uses a different asyncio loop.
  185. self.pp_locks = [
  186. asyncio.Lock()
  187. for _ in range(self.parallel_config.pipeline_parallel_size)
  188. ]
  189. tasks = [
  190. asyncio.create_task(
  191. _run_task_with_lock(self.driver_exec_model, self.pp_locks[0],
  192. execute_model_req))
  193. ]
  194. for pp_rank, driver_worker in enumerate(self.tp_driver_workers,
  195. start=1):
  196. tasks.append(
  197. asyncio.create_task(
  198. _run_task_with_lock(driver_worker.execute_method_async,
  199. self.pp_locks[pp_rank],
  200. "execute_model", execute_model_req)))
  201. results = await asyncio.gather(*tasks)
  202. # Only the last PP stage has the final results.
  203. return results[-1]
  204. async def _start_worker_execution_loop(self):
  205. coros = [
  206. worker.execute_method_async("start_worker_execution_loop")
  207. for worker in self.non_driver_workers
  208. ]
  209. return await asyncio.gather(*coros)