tpu_executor.py 5.7 KB

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