tpu_executor.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. from typing import Any, Dict, List, Optional, Set, Tuple
  2. import torch
  3. from loguru import logger
  4. from aphrodite.common.sequence import ExecuteModelRequest, SamplerOutput
  5. from aphrodite.common.utils import (get_distributed_init_method, get_ip,
  6. get_open_port, make_async)
  7. from aphrodite.executor.executor_base import ExecutorAsyncBase, ExecutorBase
  8. from aphrodite.lora.request import LoRARequest
  9. class TPUExecutor(ExecutorBase):
  10. uses_ray: bool = False
  11. def _init_executor(self) -> None:
  12. assert not self.scheduler_config.chunked_prefill_enabled, (
  13. "Chunked prefill is not yet supported for TPU backend")
  14. assert not self.speculative_config, (
  15. "Speculative decoding is not yet supported for TPU backend")
  16. if self.model_config.dtype in (torch.float16, torch.float32):
  17. logger.warning("The TPU backend currently does not support "
  18. f"{self.model_config.dtype}. "
  19. "Using bfloat16 instead.")
  20. self.model_config.dtype = torch.bfloat16
  21. # Instantiate the worker and load the model to the device.
  22. self.driver_worker = self._create_worker()
  23. self.driver_worker.init_device()
  24. self.driver_worker.load_model()
  25. def _get_worker_kwargs(
  26. self,
  27. local_rank: int = 0,
  28. rank: int = 0,
  29. distributed_init_method: Optional[str] = None,
  30. ) -> Dict[str, Any]:
  31. """Return worker init args for a given rank."""
  32. if distributed_init_method is None:
  33. distributed_init_method = get_distributed_init_method(
  34. get_ip(), get_open_port())
  35. return dict(
  36. model_config=self.model_config,
  37. parallel_config=self.parallel_config,
  38. scheduler_config=self.scheduler_config,
  39. device_config=self.device_config,
  40. cache_config=self.cache_config,
  41. load_config=self.load_config,
  42. local_rank=local_rank,
  43. rank=rank,
  44. distributed_init_method=distributed_init_method,
  45. multimodal_config=self.multimodal_config,
  46. is_driver_worker=rank == 0,
  47. )
  48. def _create_worker(
  49. self,
  50. local_rank: int = 0,
  51. rank: int = 0,
  52. distributed_init_method: Optional[str] = None,
  53. ):
  54. from aphrodite.task_handler.tpu_worker import TPUWorker
  55. worker = TPUWorker(**self._get_worker_kwargs(local_rank, rank,
  56. distributed_init_method))
  57. return worker
  58. def initialize_cache(
  59. self,
  60. num_gpu_blocks: int,
  61. num_cpu_blocks: int,
  62. ) -> None:
  63. """Initialize the KV cache by invoking the underlying worker."""
  64. # NOTE: This is logged in the executor because there can be >1 worker
  65. # with other executors. We could log in the engine level, but work
  66. # remains to abstract away the device for non-GPU configurations.
  67. logger.info(f"# TPU blocks: {num_gpu_blocks}, "
  68. f"# CPU blocks: {num_cpu_blocks}")
  69. logger.info(
  70. f"Minimum concurrency: {num_gpu_blocks * self.cache_config.block_size / self.scheduler_config.max_model_len:.2f}x" # noqa: E501
  71. )
  72. self.driver_worker.initialize_cache(num_gpu_blocks, num_cpu_blocks)
  73. def determine_num_available_blocks(self) -> Tuple[int, int]:
  74. """Determine the number of available KV blocks by invoking the
  75. underlying worker.
  76. """
  77. return self.driver_worker.determine_num_available_blocks()
  78. def execute_model(
  79. self,
  80. execute_model_req: ExecuteModelRequest,
  81. ) -> List[SamplerOutput]:
  82. output = self.driver_worker.execute_model(execute_model_req)
  83. return output
  84. def add_lora(self, lora_request: LoRARequest) -> bool:
  85. raise NotImplementedError(
  86. "LoRA is currently not supported by the TPU backend.")
  87. def remove_lora(self, lora_id: int) -> bool:
  88. raise NotImplementedError(
  89. "LoRA is currently not supported by the TPU backend.")
  90. def pin_lora(self, lora_id: int) -> bool:
  91. raise NotImplementedError(
  92. "LoRA is currently not supported by the TPU backend.")
  93. def list_loras(self) -> Set[int]:
  94. raise NotImplementedError(
  95. "LoRA is currently not supported by the TPU backend.")
  96. def add_prompt_adapter(self, prompt_adapter_request) -> bool:
  97. raise NotImplementedError(
  98. "Soft prompt is currently not supported by the TPU backend.")
  99. def remove_prompt_adapter(self, prompt_adapter_id: int) -> bool:
  100. raise NotImplementedError(
  101. "Soft prompt is currently not supported by the TPU backend.")
  102. def pin_prompt_adapter(self, prompt_adapter_id: int) -> bool:
  103. raise NotImplementedError(
  104. "Soft prompt is currently not supported by the TPU backend.")
  105. def list_prompt_adapters(self) -> Set[int]:
  106. raise NotImplementedError(
  107. "Soft prompt is currently not supported by the TPU backend.")
  108. def check_health(self) -> None:
  109. # TPUExecutor will always be healthy as long as it's running.
  110. return
  111. class TPUExecutorAsync(TPUExecutor, ExecutorAsyncBase):
  112. async def execute_model_async(
  113. self,
  114. sexecute_model_req: ExecuteModelRequest,
  115. ) -> SamplerOutput:
  116. output = await make_async(self.driver_worker.execute_model
  117. )(sexecute_model_req)
  118. return output