worker.py 17 KB

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