worker.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. """A GPU worker class."""
  2. import gc
  3. import os
  4. from typing import Any, Dict, List, Optional, Set, Tuple, Union
  5. import torch
  6. import torch.distributed
  7. from loguru import logger
  8. from aphrodite.common.config import (CacheConfig, DeviceConfig, LoadConfig,
  9. LoRAConfig, ModelConfig, ParallelConfig,
  10. SchedulerConfig, VisionLanguageConfig)
  11. from aphrodite.common.sequence import (ExecuteModelRequest, PoolerOutput,
  12. SamplerOutput)
  13. from aphrodite.distributed import (broadcast_tensor_dict,
  14. ensure_model_parallel_initialized,
  15. init_distributed_environment,
  16. set_custom_all_reduce)
  17. from aphrodite.lora.request import LoRARequest
  18. from aphrodite.modeling import set_random_seed
  19. from aphrodite.task_handler.cache_engine import CacheEngine
  20. from aphrodite.task_handler.embedding_model_runner import EmbeddingModelRunner
  21. from aphrodite.task_handler.model_runner import ModelRunner
  22. from aphrodite.task_handler.worker_base import WorkerBase
  23. class Worker(WorkerBase):
  24. """A worker class that executes (a partition of) the model on a GPU.
  25. Each worker is associated with a single GPU. The worker is responsible for
  26. maintaining the KV cache and executing the model on the GPU. In case of
  27. distributed inference, each worker is assigned a partition of the model.
  28. """
  29. def __init__(
  30. self,
  31. model_config: ModelConfig,
  32. parallel_config: ParallelConfig,
  33. scheduler_config: SchedulerConfig,
  34. device_config: DeviceConfig,
  35. cache_config: CacheConfig,
  36. load_config: LoadConfig,
  37. local_rank: int,
  38. rank: int,
  39. distributed_init_method: str,
  40. lora_config: Optional[LoRAConfig] = None,
  41. vision_language_config: Optional[VisionLanguageConfig] = None,
  42. is_driver_worker: bool = False,
  43. ) -> None:
  44. self.model_config = model_config
  45. self.parallel_config = parallel_config
  46. self.scheduler_config = scheduler_config
  47. self.device_config = device_config
  48. self.cache_config = cache_config
  49. self.local_rank = local_rank
  50. self.rank = rank
  51. self.distributed_init_method = distributed_init_method
  52. self.lora_config = lora_config
  53. self.load_config = load_config
  54. self.is_driver_worker = is_driver_worker
  55. if self.is_driver_worker:
  56. assert self.rank == 0, "The driver worker must have rank 0."
  57. if self.model_config.trust_remote_code:
  58. # note: lazy import to avoid importing torch before initializing
  59. from aphrodite.common.utils import init_cached_hf_modules
  60. init_cached_hf_modules()
  61. self.vision_language_config = vision_language_config
  62. if self.vision_language_config:
  63. assert not self.lora_config, (
  64. "To be tested: vision language model with LoRA settings.")
  65. ModelRunnerClass = (EmbeddingModelRunner if
  66. self.model_config.embedding_mode else ModelRunner)
  67. self.model_runner = ModelRunnerClass(
  68. model_config,
  69. parallel_config,
  70. scheduler_config,
  71. device_config,
  72. cache_config,
  73. load_config=load_config,
  74. lora_config=self.lora_config,
  75. kv_cache_dtype=self.cache_config.cache_dtype,
  76. is_driver_worker=is_driver_worker,
  77. vision_language_config=vision_language_config,
  78. )
  79. # Uninitialized cache engine. Will be initialized by
  80. # initialize_cache.
  81. self.cache_engine: CacheEngine
  82. # Initialize gpu_cache as embedding models don't initialize kv_caches
  83. self.gpu_cache: Optional[List[torch.tensor]] = None
  84. def init_device(self) -> None:
  85. if self.device_config.device.type == "cuda":
  86. # torch.distributed.all_reduce does not free the input tensor until
  87. # the synchronization point. This causes the memory usage to grow
  88. # as the number of all_reduce calls increases. This env var disables
  89. # this behavior.
  90. # Related issue:
  91. # https://discuss.pytorch.org/t/cuda-allocation-lifetime-for-inputs-to-distributed-all-reduce/191573
  92. os.environ["TORCH_NCCL_AVOID_RECORD_STREAMS"] = "1"
  93. # This env var set by Ray causes exceptions with graph building.
  94. os.environ.pop("NCCL_ASYNC_ERROR_HANDLING", None)
  95. self.device = torch.device(f"cuda:{self.local_rank}")
  96. torch.cuda.set_device(self.device)
  97. _check_if_gpu_supports_dtype(self.model_config.dtype)
  98. torch.cuda.empty_cache()
  99. self.init_gpu_memory = torch.cuda.mem_get_info()[0]
  100. else:
  101. raise RuntimeError(
  102. f"Not support device type: {self.device_config.device}")
  103. # Initialize the distributed environment.
  104. init_worker_distributed_environment(self.parallel_config, self.rank,
  105. self.distributed_init_method,
  106. self.local_rank)
  107. # Set random seed.
  108. set_random_seed(self.model_config.seed)
  109. def load_model(self):
  110. self.model_runner.load_model()
  111. @torch.inference_mode()
  112. def determine_num_available_blocks(self) -> Tuple[int, int]:
  113. """Profiles the peak memory usage of the model to determine how many
  114. KV blocks may be allocated without OOMs.
  115. The engine will first conduct a profiling of the existing memory usage.
  116. Then, it calculate the maximum possible number of GPU and CPU blocks
  117. that can be allocated with the remaining free memory.
  118. .. tip::
  119. You may limit the usage of GPU memory
  120. by adjusting the `gpu_memory_utilization` parameter.
  121. """
  122. # Profile the memory usage of the model and get the maximum number of
  123. # cache blocks that can be allocated with the remaining free memory.
  124. torch.cuda.empty_cache()
  125. # Execute a forward pass with dummy inputs to profile the memory usage
  126. # of the model.
  127. self.model_runner.profile_run()
  128. # Calculate the number of blocks that can be allocated with the
  129. # profiled peak memory.
  130. torch.cuda.synchronize()
  131. free_gpu_memory, total_gpu_memory = torch.cuda.mem_get_info()
  132. # NOTE: Here we assume that the other processes using the same
  133. # GPU did not change their memory usage during the profiling.
  134. peak_memory = self.init_gpu_memory - free_gpu_memory
  135. assert peak_memory > 0, (
  136. "Error in memory profiling. This happens when the GPU memory was "
  137. "not properly cleaned up before initializing Aphrodite.")
  138. cache_block_size = self.get_cache_block_size_bytes()
  139. num_gpu_blocks = int(
  140. (total_gpu_memory * self.cache_config.gpu_memory_utilization -
  141. peak_memory) // cache_block_size)
  142. num_cpu_blocks = int(self.cache_config.swap_space_bytes //
  143. cache_block_size)
  144. num_gpu_blocks = max(num_gpu_blocks, 0)
  145. num_cpu_blocks = max(num_cpu_blocks, 0)
  146. if self.model_runner.lora_manager:
  147. self.model_runner.remove_all_loras()
  148. gc.collect()
  149. torch.cuda.empty_cache()
  150. return num_gpu_blocks, num_cpu_blocks
  151. def initialize_cache(self, num_gpu_blocks: int,
  152. num_cpu_blocks: int) -> None:
  153. """Allocate GPU and CPU KV cache with the specified number of blocks.
  154. This also warms up the model, which may record CUDA graphs.
  155. """
  156. raise_if_cache_size_invalid(num_gpu_blocks,
  157. self.cache_config.block_size,
  158. self.model_config.max_model_len)
  159. self.cache_config.num_gpu_blocks = num_gpu_blocks
  160. self.cache_config.num_cpu_blocks = num_cpu_blocks
  161. self._init_cache_engine()
  162. self._warm_up_model()
  163. def _init_cache_engine(self):
  164. assert self.cache_config.num_gpu_blocks is not None
  165. self.cache_engine = CacheEngine(self.cache_config, self.model_config,
  166. self.parallel_config)
  167. self.gpu_cache = self.cache_engine.gpu_cache
  168. def _warm_up_model(self) -> None:
  169. if not self.model_config.enforce_eager:
  170. self.model_runner.capture_model(self.gpu_cache)
  171. # Reset the seed to ensure that the random state is not affected by
  172. # the model initialization and profiling.
  173. set_random_seed(self.model_config.seed)
  174. def cache_swap(
  175. self,
  176. blocks_to_swap_in: torch.Tensor,
  177. blocks_to_swap_out: torch.Tensor,
  178. blocks_to_copy: torch.Tensor,
  179. ) -> None:
  180. # Issue cache operations.
  181. if blocks_to_swap_in.numel() > 0:
  182. self.cache_engine.swap_in(blocks_to_swap_in)
  183. if blocks_to_swap_out.numel() > 0:
  184. self.cache_engine.swap_out(blocks_to_swap_out)
  185. if blocks_to_copy.numel() > 0:
  186. self.cache_engine.copy(blocks_to_copy)
  187. @torch.inference_mode()
  188. def execute_model(
  189. self,
  190. execute_model_req: Optional[ExecuteModelRequest] = None
  191. ) -> List[Union[SamplerOutput, PoolerOutput]]:
  192. if execute_model_req is None:
  193. seq_group_metadata_list = None
  194. else:
  195. seq_group_metadata_list = execute_model_req.seq_group_metadata_list
  196. blocks_to_swap_in: torch.Tensor
  197. blocks_to_swap_out: torch.Tensor
  198. blocks_to_copy: torch.Tensor
  199. if self.is_driver_worker:
  200. assert seq_group_metadata_list is not None
  201. assert execute_model_req is not None
  202. num_seq_groups = len(seq_group_metadata_list)
  203. # `blocks_to_swap_in` and `blocks_to_swap_out` are cpu tensors.
  204. # they contain parameters to launch cudamemcpyasync.
  205. blocks_to_swap_in = torch.tensor(
  206. execute_model_req.blocks_to_swap_in,
  207. device="cpu",
  208. dtype=torch.int64).view(-1, 2)
  209. blocks_to_swap_out = torch.tensor(
  210. execute_model_req.blocks_to_swap_out,
  211. device="cpu",
  212. dtype=torch.int64).view(-1, 2)
  213. # `blocks_to_copy` is a gpu tensor. The src and tgt of
  214. # blocks to copy are in the same device, and `blocks_to_copy`
  215. # can be used directly within cuda kernels.
  216. blocks_to_copy = torch.tensor(execute_model_req.blocks_to_copy,
  217. device=self.device,
  218. dtype=torch.int64).view(-1, 2)
  219. data: Dict[str, Any] = {
  220. "num_seq_groups": num_seq_groups,
  221. "blocks_to_swap_in": blocks_to_swap_in,
  222. "blocks_to_swap_out": blocks_to_swap_out,
  223. "blocks_to_copy": blocks_to_copy,
  224. }
  225. broadcast_tensor_dict(data, src=0)
  226. else:
  227. data = broadcast_tensor_dict(src=0)
  228. num_seq_groups = data["num_seq_groups"]
  229. blocks_to_swap_in = data["blocks_to_swap_in"]
  230. blocks_to_swap_out = data["blocks_to_swap_out"]
  231. blocks_to_copy = data["blocks_to_copy"]
  232. self.cache_swap(blocks_to_swap_in, blocks_to_swap_out, blocks_to_copy)
  233. # If there is no input, we don't need to execute the model.
  234. if num_seq_groups == 0:
  235. return []
  236. output = self.model_runner.execute_model(seq_group_metadata_list,
  237. self.gpu_cache)
  238. # Worker only supports single-step execution. Wrap the output in a list
  239. # to conform to interface.
  240. return [output]
  241. def add_lora(self, lora_request: LoRARequest) -> bool:
  242. return self.model_runner.add_lora(lora_request)
  243. def remove_lora(self, lora_id: int) -> bool:
  244. return self.model_runner.remove_lora(lora_id)
  245. def list_loras(self) -> Set[int]:
  246. return self.model_runner.list_loras()
  247. @property
  248. def max_model_len(self) -> int:
  249. return self.model_config.max_model_len
  250. @property
  251. def vocab_size(self) -> int:
  252. return self.model_runner.vocab_size
  253. def get_cache_block_size_bytes(self) -> int:
  254. """Get the size of the KV cache block size in bytes.
  255. """
  256. return CacheEngine.get_cache_block_size(self.cache_config,
  257. self.model_config,
  258. self.parallel_config)
  259. def init_worker_distributed_environment(
  260. parallel_config: ParallelConfig,
  261. rank: int,
  262. distributed_init_method: Optional[str] = None,
  263. local_rank: int = -1,
  264. ) -> None:
  265. """Initialize the distributed environment."""
  266. set_custom_all_reduce(not parallel_config.disable_custom_all_reduce)
  267. init_distributed_environment(parallel_config.world_size, rank,
  268. distributed_init_method, local_rank)
  269. ensure_model_parallel_initialized(parallel_config.tensor_parallel_size,
  270. parallel_config.pipeline_parallel_size)
  271. def _check_if_gpu_supports_dtype(torch_dtype: torch.dtype):
  272. # Check if the GPU supports the dtype.
  273. if torch_dtype == torch.bfloat16:
  274. compute_capability = torch.cuda.get_device_capability()
  275. if compute_capability[0] < 8:
  276. gpu_name = torch.cuda.get_device_name()
  277. raise ValueError(
  278. "Bfloat16 is only supported on GPUs with compute capability "
  279. f"of at least 8.0. Your {gpu_name} GPU has compute capability "
  280. f"{compute_capability[0]}.{compute_capability[1]}. "
  281. "You can use float16 instead by explicitly setting the"
  282. "`dtype` flag in CLI, for example: --dtype=half.")
  283. def raise_if_cache_size_invalid(num_gpu_blocks, block_size,
  284. max_model_len) -> None:
  285. if num_gpu_blocks <= 0:
  286. raise ValueError("No available memory for the cache blocks. "
  287. "Try increasing `gpu_memory_utilization` when "
  288. "initializing the engine.")
  289. max_seq_len = block_size * num_gpu_blocks
  290. logger.info(f"Maximum sequence length allowed in the cache: "
  291. f"{max_seq_len}")
  292. if max_model_len > max_seq_len:
  293. raise ValueError(
  294. f"The model's max seq len ({max_model_len}) "
  295. "is larger than the maximum number of tokens that can be "
  296. f"stored in KV cache ({max_seq_len}). Try increasing "
  297. "`gpu_memory_utilization` or decreasing `max_model_len` when "
  298. "initializing the engine.")