worker.py 19 KB

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