tpu_worker.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. import os
  2. from typing import List, Optional, Tuple, Union
  3. import torch
  4. import torch_xla.core.xla_model as xm
  5. import torch_xla.experimental.dynamo_set_buffer_donor # noqa: F401
  6. import torch_xla.runtime as xr
  7. from aphrodite.common.config import (CacheConfig, DeviceConfig, LoadConfig,
  8. ModelConfig, MultiModalConfig,
  9. ParallelConfig, SchedulerConfig)
  10. from aphrodite.common.sequence import ExecuteModelRequest
  11. from aphrodite.common.utils import STR_DTYPE_TO_TORCH_DTYPE, get_dtype_size
  12. from aphrodite.distributed import (ensure_model_parallel_initialized,
  13. init_distributed_environment)
  14. from aphrodite.modeling import set_random_seed
  15. from aphrodite.task_handler.tpu_model_runner import TPUModelRunner
  16. from aphrodite.task_handler.worker_base import (LocalOrDistributedWorkerBase,
  17. LoraNotSupportedWorkerBase,
  18. WorkerInput)
  19. class TPUWorker(LoraNotSupportedWorkerBase, LocalOrDistributedWorkerBase):
  20. def __init__(
  21. self,
  22. model_config: ModelConfig,
  23. parallel_config: ParallelConfig,
  24. scheduler_config: SchedulerConfig,
  25. device_config: DeviceConfig,
  26. cache_config: CacheConfig,
  27. load_config: LoadConfig,
  28. multimodal_config: Optional[MultiModalConfig],
  29. local_rank: int,
  30. rank: int,
  31. distributed_init_method: str,
  32. is_driver_worker: bool,
  33. ) -> None:
  34. self.model_config = model_config
  35. self.parallel_config = parallel_config
  36. self.parallel_config.rank = rank
  37. self.scheduler_config = scheduler_config
  38. self.device_config = device_config
  39. self.cache_config = cache_config
  40. self.load_config = load_config
  41. self.multimodal_config = multimodal_config
  42. self.local_rank = local_rank
  43. self.rank = rank
  44. self.distributed_init_method = distributed_init_method
  45. self.is_driver_worker = is_driver_worker
  46. assert self.device_config.device_type == "tpu"
  47. if self.cache_config.cache_dtype == "auto":
  48. self.cache_dtype = self.model_config.dtype
  49. else:
  50. self.cache_dtype = STR_DTYPE_TO_TORCH_DTYPE[
  51. self.cache_config.cache_dtype]
  52. self.model_runner: TPUModelRunner = TPUModelRunner(
  53. model_config,
  54. parallel_config,
  55. scheduler_config,
  56. device_config,
  57. cache_config,
  58. load_config,
  59. multimodal_config,
  60. is_driver_worker=is_driver_worker)
  61. def init_device(self) -> None:
  62. os.environ["PJRT_DEVICE"] = "TPU"
  63. self.device = xm.xla_device()
  64. self.device_config.device = self.device
  65. torch.set_grad_enabled(False)
  66. torch.set_default_dtype(self.model_config.dtype)
  67. # NOTE: This is just a hack to initialize the TP group.
  68. # This cannot perform the actual communication ops.
  69. init_distributed_environment(
  70. world_size=self.parallel_config.world_size,
  71. rank=self.rank,
  72. local_rank=self.local_rank,
  73. distributed_init_method=self.distributed_init_method,
  74. backend="gloo",
  75. )
  76. ensure_model_parallel_initialized(
  77. self.parallel_config.tensor_parallel_size,
  78. self.parallel_config.pipeline_parallel_size)
  79. # Set random seed.
  80. set_random_seed(self.model_config.seed)
  81. xm.set_rng_state(self.model_config.seed, self.device)
  82. # Increase the cache size limit, which is the maximum number of
  83. # dynamo graphs that can be compiled.
  84. # NOTE: Usually, we compile 10-15 graphs for prefill and
  85. # 30-40 graphs for decode. 128 is an arbitrary safe number.
  86. torch._dynamo.config.cache_size_limit = 128
  87. # Use persistent cache to avoid XLA recompilation.
  88. # NOTE: This does not completely eliminate the recompilation
  89. # overhead because dynamo does not cache the compiled results.
  90. APHRODITE_XLA_CACHE_PATH = os.getenv("APHRODITE_XLA_CACHE_PATH",
  91. "~/.aphrodite/xla_cache/")
  92. xr.initialize_cache(os.path.expanduser(APHRODITE_XLA_CACHE_PATH),
  93. readonly=False)
  94. def load_model(self):
  95. self.model_runner.load_model()
  96. def determine_num_available_blocks(self) -> Tuple[int, int]:
  97. num_layers = self.model_config.get_num_layers(self.parallel_config)
  98. head_size = self.model_config.get_head_size()
  99. num_kv_heads = self.model_config.get_num_kv_heads(self.parallel_config)
  100. kv_caches = [(None, None) for _ in range(num_layers)]
  101. self.model_runner._dummy_run(
  102. batch_size=1,
  103. seq_len=self.scheduler_config.max_num_batched_tokens,
  104. kv_caches=kv_caches,
  105. is_prompt=True,
  106. )
  107. # Synchronize before measuring the memory usage.
  108. xm.wait_device_ops()
  109. dtype_btyes = get_dtype_size(self.cache_dtype)
  110. block_size = self.cache_config.block_size
  111. block_size_bytes = (dtype_btyes * block_size * num_layers * 2 *
  112. head_size * num_kv_heads)
  113. # Calculate the TPU KV cache size based on profiling.
  114. m = xm.get_memory_info(self.device)
  115. total_memory_size = m["bytes_limit"]
  116. usable_memory_size = int(total_memory_size *
  117. self.cache_config.gpu_memory_utilization)
  118. profiled = m["bytes_used"] # Weights + intermediate activations.
  119. tpu_kv_cache_bytes = max(usable_memory_size - profiled, 0)
  120. num_tpu_blocks = tpu_kv_cache_bytes // block_size_bytes
  121. num_tpu_blocks = (num_tpu_blocks // 8) * 8 # Round down to 8.
  122. # Calculate the CPU KV cache size based on the config.
  123. num_cpu_blocks = (self.cache_config.swap_space_bytes //
  124. block_size_bytes)
  125. num_cpu_blocks = (num_cpu_blocks // 8) * 8 # Round down to 8.
  126. return num_tpu_blocks, num_cpu_blocks
  127. def initialize_cache(
  128. self,
  129. num_gpu_blocks: int,
  130. num_cpu_blocks: int,
  131. ) -> None:
  132. self.cache_config.num_gpu_blocks = num_gpu_blocks
  133. self.cache_config.num_cpu_blocks = num_cpu_blocks
  134. self.block_size = self.cache_config.block_size
  135. dtype = self.cache_dtype
  136. num_layers = self.model_config.get_num_layers(self.parallel_config)
  137. num_kv_heads = self.model_config.get_num_kv_heads(self.parallel_config)
  138. head_size = self.model_config.get_head_size()
  139. self.cpu_cache: List[Tuple[torch.Tensor, torch.Tensor]] = []
  140. self.tpu_cache: List[Tuple[torch.Tensor, torch.Tensor]] = []
  141. tpu_cache_shape = self.model_runner.attn_backend.get_kv_cache_shape(
  142. num_gpu_blocks, self.block_size, num_kv_heads, head_size)
  143. cpu_cache_shape = self.model_runner.attn_backend.get_kv_cache_shape(
  144. num_cpu_blocks, self.block_size, num_kv_heads, head_size)
  145. for _ in range(num_layers):
  146. tpu_k_cache = torch.zeros(tpu_cache_shape,
  147. dtype=dtype,
  148. device=self.device)
  149. tpu_v_cache = torch.zeros_like(tpu_k_cache)
  150. self.tpu_cache.append((tpu_k_cache, tpu_v_cache))
  151. cpu_k_cache = torch.zeros(cpu_cache_shape,
  152. dtype=dtype,
  153. device="cpu")
  154. cpu_v_cache = torch.zeros_like(cpu_k_cache)
  155. self.cpu_cache.append((cpu_k_cache, cpu_v_cache))
  156. self._warmup_model()
  157. def _warmup_model(self) -> None:
  158. # FIXME: Here we are abusing `enforce_eager` which is defined
  159. # for CUDA graphs. We should refactor this part.
  160. if not self.model_config.enforce_eager:
  161. # Warm up the model with all possible input shapes so that
  162. # compilation never happens during the actual execution.
  163. # This may take ~30 mins for the first run and ~20 mins for the
  164. # subsequent runs.
  165. # If `enforce_eager` is True, the ahead-of-time compilation is
  166. # skipped and the compilation happens during the actual execution,
  167. # which is bad for performance but useful for development.
  168. self.model_runner.warmup_model(self.tpu_cache)
  169. def get_cache_block_size_bytes(self) -> int:
  170. head_size = self.model_config.get_head_size()
  171. num_heads = self.model_config.get_num_kv_heads(self.parallel_config)
  172. num_layers = self.model_config.get_num_layers(self.parallel_config)
  173. key_cache_block = self.cache_config.block_size * num_heads * head_size
  174. value_cache_block = key_cache_block
  175. total = num_layers * (key_cache_block + value_cache_block)
  176. dtype_size = get_dtype_size(self.cache_dtype)
  177. return dtype_size * total
  178. @property
  179. def do_metadata_broadcast(self) -> bool:
  180. # TODO: Support TP.
  181. return False
  182. @property
  183. def kv_cache(self) -> Optional[List[List[torch.Tensor]]]:
  184. # NOTE: This assumes virtual_engine == 0, i.e., no pipeline
  185. # parallelism.
  186. return [self.tpu_cache]
  187. def prepare_worker_input(
  188. self,
  189. execute_model_req: ExecuteModelRequest,
  190. ) -> WorkerInput:
  191. virtual_engine = execute_model_req.virtual_engine
  192. num_seq_groups = len(execute_model_req.seq_group_metadata_list)
  193. blocks_to_swap_in = _make_src_to_dst(
  194. execute_model_req.blocks_to_swap_in, "cpu", self.device)
  195. blocks_to_swap_out = _make_src_to_dst(
  196. execute_model_req.blocks_to_swap_out, self.device, "cpu")
  197. blocks_to_copy = _make_src_to_dst(execute_model_req.blocks_to_copy,
  198. self.device, self.device)
  199. return WorkerInput(
  200. num_seq_groups=num_seq_groups,
  201. blocks_to_swap_in=blocks_to_swap_in,
  202. blocks_to_swap_out=blocks_to_swap_out,
  203. blocks_to_copy=blocks_to_copy,
  204. virtual_engine=virtual_engine,
  205. )
  206. def execute_worker(self, worker_input: WorkerInput) -> None:
  207. virtual_engine = worker_input.virtual_engine
  208. assert virtual_engine == 0
  209. attn_backend = self.model_runner.attn_backend
  210. num_layers = self.model_config.get_num_layers(self.parallel_config)
  211. # Issue cache operations.
  212. if worker_input.blocks_to_swap_in is not None:
  213. src_indices, dst_indices = worker_input.blocks_to_swap_in
  214. if src_indices.numel() > 0:
  215. # Swap from CPU to TPU.
  216. for i in range(num_layers):
  217. tpu_k_cache, tpu_v_cache = self.tpu_cache[i]
  218. cpu_k_cache, cpu_v_cache = self.cpu_cache[i]
  219. k = cpu_k_cache[:, src_indices].to(self.device)
  220. v = cpu_v_cache[:, src_indices].to(self.device)
  221. _insert_kv(k, v, dst_indices, tpu_k_cache, tpu_v_cache)
  222. if worker_input.blocks_to_swap_out is not None:
  223. src_indices, dst_indices = worker_input.blocks_to_swap_out
  224. if src_indices.numel() > 0:
  225. # Swap from TPU to CPU.
  226. for i in range(num_layers):
  227. tpu_k_cache, tpu_v_cache = self.tpu_cache[i]
  228. cpu_k_cache, cpu_v_cache = self.cpu_cache[i]
  229. cpu_k_cache[:, dst_indices] = tpu_k_cache[:, src_indices]
  230. cpu_v_cache[:, dst_indices] = tpu_v_cache[:, src_indices]
  231. if worker_input.blocks_to_copy is not None:
  232. src_indices, dst_indices = worker_input.blocks_to_copy
  233. if src_indices.numel() > 0:
  234. attn_backend.copy_blocks(self.tpu_cache,
  235. (src_indices, dst_indices))
  236. def _make_src_to_dst(
  237. mapping: List[Tuple[int, int]],
  238. src_device: Union[torch.device, str],
  239. dst_device: Union[torch.device, str],
  240. ) -> Tuple[torch.Tensor, torch.Tensor]:
  241. src_indices = [i for i, _ in mapping]
  242. dst_indices = [i for _, i in mapping]
  243. src_indices = torch.tensor(src_indices,
  244. device=src_device,
  245. dtype=torch.int64)
  246. dst_indices = torch.tensor(dst_indices,
  247. device=dst_device,
  248. dtype=torch.int64)
  249. return src_indices, dst_indices
  250. @torch.compile(backend="openxla")
  251. def _insert_kv(
  252. k: torch.Tensor,
  253. v: torch.Tensor,
  254. indices: torch.Tensor,
  255. tpu_k_cache: torch.Tensor,
  256. tpu_v_cache: torch.Tensor,
  257. ) -> None:
  258. torch.ops.xla.dynamo_set_buffer_donor_(tpu_k_cache, True)
  259. torch.ops.xla.dynamo_set_buffer_donor_(tpu_v_cache, True)
  260. tpu_k_cache[:, indices] = k
  261. tpu_v_cache[:, indices] = v