cache_engine.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. """CacheEngine class for managing the KV cache."""
  2. from typing import Dict, List, Tuple
  3. import torch
  4. from aphrodite._C import cache_ops
  5. from aphrodite.common.config import CacheConfig, ModelConfig, ParallelConfig
  6. from aphrodite.common.logger import init_logger
  7. from aphrodite.common.utils import in_wsl, STR_DTYPE_TO_TORCH_DTYPE
  8. logger = init_logger(__name__)
  9. KVCache = Tuple[torch.Tensor, torch.Tensor]
  10. class CacheEngine:
  11. """Manages the KV cache.
  12. This class is responsible for initializing and managing the GPU and CPU KV
  13. caches. It also provides methods for performing KV cache operations, such
  14. as swapping and copying.
  15. """
  16. def __init__(
  17. self,
  18. cache_config: CacheConfig,
  19. model_config: ModelConfig,
  20. parallel_config: ParallelConfig,
  21. ) -> None:
  22. self.cache_config = cache_config
  23. self.model_config = model_config
  24. self.parallel_config = parallel_config
  25. self.head_size = model_config.get_head_size()
  26. self.num_layers = model_config.get_num_layers(parallel_config)
  27. self.num_heads = model_config.get_num_kv_heads(parallel_config)
  28. self.block_size = cache_config.block_size
  29. self.num_gpu_blocks = cache_config.num_gpu_blocks
  30. self.num_cpu_blocks = cache_config.num_cpu_blocks
  31. if cache_config.cache_dtype == "auto":
  32. self.dtype = model_config.dtype
  33. else:
  34. self.dtype = STR_DTYPE_TO_TORCH_DTYPE[cache_config.cache_dtype]
  35. # Initialize the cache.
  36. self.gpu_cache = self.allocate_gpu_cache()
  37. self.cpu_cache = self.allocate_cpu_cache()
  38. # Initialize the stream for caching operations.
  39. self.cache_stream = torch.cuda.Stream()
  40. assert self.cache_stream != torch.cuda.current_stream()
  41. # Initialize the events for stream synchronization.
  42. self.events = [torch.cuda.Event() for _ in range(self.num_layers)]
  43. def get_key_block_shape(self) -> Tuple[int, int, int, int]:
  44. element_size = torch.tensor([], dtype=self.dtype).element_size()
  45. x = 16 // element_size
  46. return (
  47. self.num_heads,
  48. self.head_size // x,
  49. self.block_size,
  50. x,
  51. )
  52. def get_value_block_shape(self) -> Tuple[int, int, int]:
  53. return (
  54. self.num_heads,
  55. self.head_size,
  56. self.block_size,
  57. )
  58. def allocate_gpu_cache(self) -> List[KVCache]:
  59. gpu_cache: List[KVCache] = []
  60. key_block_shape = self.get_key_block_shape()
  61. value_block_shape = self.get_value_block_shape()
  62. for _ in range(self.num_layers):
  63. key_blocks = torch.empty(
  64. size=(self.num_gpu_blocks, *key_block_shape),
  65. dtype=self.dtype,
  66. device="cuda",
  67. )
  68. value_blocks = torch.empty(
  69. size=(self.num_gpu_blocks, *value_block_shape),
  70. dtype=self.dtype,
  71. device="cuda",
  72. )
  73. gpu_cache.append((key_blocks, value_blocks))
  74. return gpu_cache
  75. def allocate_cpu_cache(self) -> List[KVCache]:
  76. cpu_cache: List[KVCache] = []
  77. key_block_shape = self.get_key_block_shape()
  78. value_block_shape = self.get_value_block_shape()
  79. pin_memory = not in_wsl()
  80. if not pin_memory:
  81. # Pinning memory in WSL is not supported.
  82. # https://docs.nvidia.com/cuda/wsl-user-guide/index.html#known-limitations-for-linux-cuda-applications
  83. logger.warning("Using 'pin_memory=False' as WSL is detected. "
  84. "This may slow down the performance.")
  85. for _ in range(self.num_layers):
  86. key_blocks = torch.empty(
  87. size=(self.num_cpu_blocks, *key_block_shape),
  88. dtype=self.dtype,
  89. pin_memory=pin_memory,
  90. device="cpu",
  91. )
  92. value_blocks = torch.empty(
  93. size=(self.num_cpu_blocks, *value_block_shape),
  94. dtype=self.dtype,
  95. pin_memory=pin_memory,
  96. device="cpu",
  97. )
  98. cpu_cache.append((key_blocks, value_blocks))
  99. return cpu_cache
  100. def _swap(
  101. self,
  102. src: List[KVCache],
  103. dst: List[KVCache],
  104. src_to_dst: Dict[int, int],
  105. ) -> None:
  106. with torch.cuda.stream(self.cache_stream):
  107. for i in range(self.num_layers):
  108. src_key_cache, src_value_cache = src[i]
  109. dst_key_cache, dst_value_cache = dst[i]
  110. # Copy the key blocks.
  111. cache_ops.swap_blocks(src_key_cache, dst_key_cache, src_to_dst)
  112. # Copy the value blocks.
  113. cache_ops.swap_blocks(src_value_cache, dst_value_cache,
  114. src_to_dst)
  115. event = self.events[i]
  116. event.record(stream=self.cache_stream)
  117. def swap_in(self, src_to_dst: Dict[int, int]) -> None:
  118. self._swap(self.cpu_cache, self.gpu_cache, src_to_dst)
  119. def swap_out(self, src_to_dst: Dict[int, int]) -> None:
  120. self._swap(self.gpu_cache, self.cpu_cache, src_to_dst)
  121. def copy(self, src_to_dsts: Dict[int, List[int]]) -> None:
  122. key_caches = [key_cache for key_cache, _ in self.gpu_cache]
  123. value_caches = [value_cache for _, value_cache in self.gpu_cache]
  124. # NOTE: This operation implicitly synchronizes the CPU and GPU.
  125. cache_ops.copy_blocks(key_caches, value_caches, src_to_dsts)
  126. @staticmethod
  127. def get_cache_block_size(
  128. block_size: int,
  129. cache_dtype: str,
  130. model_config: ModelConfig,
  131. parallel_config: ParallelConfig,
  132. ) -> int:
  133. head_size = model_config.get_head_size()
  134. num_heads = model_config.get_num_kv_heads(parallel_config)
  135. num_layers = model_config.get_num_layers(parallel_config)
  136. key_cache_block = block_size * num_heads * head_size
  137. value_cache_block = key_cache_block
  138. total = num_layers * (key_cache_block + value_cache_block)
  139. if cache_dtype == "auto":
  140. dtype = model_config.dtype
  141. else:
  142. dtype = STR_DTYPE_TO_TORCH_DTYPE[cache_dtype]
  143. dtype_size = _get_dtype_size(dtype)
  144. return dtype_size * total
  145. def _get_dtype_size(dtype: torch.dtype) -> int:
  146. return torch.tensor([], dtype=dtype).element_size()