multiproc_gpu_executor.py 11 KB

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