tpu_worker.py 12 KB

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