cpu_worker.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. """A CPU worker class."""
  2. from typing import Dict, List, Optional, Tuple
  3. import torch
  4. import torch.distributed
  5. import aphrodite.common.envs as envs
  6. from aphrodite.attention import get_attn_backend
  7. from aphrodite.common.config import (CacheConfig, DeviceConfig, LoadConfig,
  8. LoRAConfig, ModelConfig, ParallelConfig,
  9. PromptAdapterConfig, SchedulerConfig)
  10. from aphrodite.common.sequence import ExecuteModelRequest
  11. from aphrodite.common.utils import STR_DTYPE_TO_TORCH_DTYPE
  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.cpu_model_runner import CPUModelRunner
  16. from aphrodite.task_handler.worker_base import (LocalOrDistributedWorkerBase,
  17. LoraNotSupportedWorkerBase,
  18. WorkerInput)
  19. APHRODITE_CPU_OMP_THREADS_BIND = envs.APHRODITE_CPU_OMP_THREADS_BIND
  20. class CPUCacheEngine:
  21. """Manages the KV cache for CPU backend.
  22. This class is responsible for initializing and managing CPU KV
  23. caches. It also provides methods for performing KV cache operations, such
  24. as copying.
  25. """
  26. def __init__(self, cache_config: CacheConfig, model_config: ModelConfig,
  27. parallel_config: ParallelConfig,
  28. device_config: DeviceConfig) -> None:
  29. assert device_config.device_type == "cpu"
  30. self.cache_config = cache_config
  31. self.model_config = model_config
  32. self.parallel_config = parallel_config
  33. self.head_size = model_config.get_head_size()
  34. self.num_layers = model_config.get_num_layers(parallel_config)
  35. self.num_heads = model_config.get_num_kv_heads(parallel_config)
  36. self.block_size = cache_config.block_size
  37. # Note: In CacheConfig, num_gpu_blocks actual is num_cpu_blocks
  38. # for CPU backend, because we want to reuse KV cache management
  39. # in the scheduler.
  40. self.num_cpu_blocks = cache_config.num_gpu_blocks
  41. if cache_config.cache_dtype == "auto":
  42. self.dtype = model_config.dtype
  43. else:
  44. self.dtype = STR_DTYPE_TO_TORCH_DTYPE[cache_config.cache_dtype]
  45. # Get attention backend.
  46. self.attn_backend = get_attn_backend(
  47. self.model_config.get_head_size(),
  48. self.model_config.get_sliding_window(),
  49. self.model_config.dtype,
  50. cache_config.cache_dtype,
  51. self.block_size,
  52. self.model_config.is_attention_free(),
  53. )
  54. # Initialize the cache.
  55. self.cpu_cache = self._allocate_kv_cache(self.num_cpu_blocks)
  56. def _allocate_kv_cache(
  57. self,
  58. num_blocks: int,
  59. ) -> List[torch.Tensor]:
  60. """Allocates KV cache on CPU."""
  61. kv_cache_shape = self.attn_backend.get_kv_cache_shape(
  62. num_blocks, self.block_size, self.num_heads, self.head_size)
  63. kv_cache: List[torch.Tensor] = []
  64. for _ in range(self.num_layers):
  65. kv_cache.append(
  66. torch.empty(kv_cache_shape, dtype=self.dtype, device="cpu"))
  67. return kv_cache
  68. def swap_in(self, src_to_dst: Dict[int, int]) -> None:
  69. raise NotImplementedError("Swap is not supported in CPUCacheEngine.")
  70. def swap_out(self, src_to_dst: Dict[int, int]) -> None:
  71. raise NotImplementedError("Swap is not supported in CPUCacheEngine.")
  72. def copy(self, src_to_dsts: Dict[int, List[int]]) -> None:
  73. self.attn_backend.copy_blocks(self.cpu_cache, src_to_dsts)
  74. @staticmethod
  75. def get_cache_block_size(
  76. block_size: int,
  77. cache_dtype: str,
  78. model_config: ModelConfig,
  79. parallel_config: ParallelConfig,
  80. ) -> int:
  81. head_size = model_config.get_head_size()
  82. num_heads = model_config.get_num_kv_heads(parallel_config)
  83. num_layers = model_config.get_num_layers(parallel_config)
  84. key_cache_block = block_size * num_heads * head_size
  85. value_cache_block = key_cache_block
  86. total = num_layers * (key_cache_block + value_cache_block)
  87. if cache_dtype == "auto":
  88. dtype = model_config.dtype
  89. else:
  90. dtype = STR_DTYPE_TO_TORCH_DTYPE[cache_dtype]
  91. dtype_size = torch.tensor([], dtype=dtype).element_size()
  92. return dtype_size * total
  93. class CPUWorker(LoraNotSupportedWorkerBase, LocalOrDistributedWorkerBase):
  94. """A worker class that executes (a partition of) the model on a CPU socket.
  95. Each worker is associated with a single CPU socket. The worker is
  96. responsible for maintaining the KV cache and executing the model on the
  97. CPU. In case of distributed inference, each worker is assigned a partition
  98. of the model.
  99. """
  100. def __init__(
  101. self,
  102. model_config: ModelConfig,
  103. parallel_config: ParallelConfig,
  104. scheduler_config: SchedulerConfig,
  105. device_config: DeviceConfig,
  106. cache_config: CacheConfig,
  107. load_config: LoadConfig,
  108. local_rank: int,
  109. rank: int,
  110. distributed_init_method: str,
  111. lora_config: Optional[LoRAConfig] = None,
  112. kv_cache_dtype: Optional[str] = "auto",
  113. prompt_adapter_config: Optional[PromptAdapterConfig] = None,
  114. is_driver_worker: bool = False,
  115. ) -> None:
  116. self.model_config = model_config
  117. self.parallel_config = parallel_config
  118. self.scheduler_config = scheduler_config
  119. self.device_config = device_config
  120. self.cache_config = cache_config
  121. self.load_config = load_config
  122. self.local_rank = local_rank
  123. self.rank = rank
  124. self.distributed_init_method = distributed_init_method
  125. self.lora_config = lora_config
  126. self.prompt_adapter_config = prompt_adapter_config
  127. self.is_driver_worker = is_driver_worker
  128. if self.is_driver_worker:
  129. assert self.rank == 0, "The driver worker must have rank 0."
  130. if self.model_config.trust_remote_code:
  131. # note: lazy import to avoid importing torch before initializing
  132. from aphrodite.common.utils import init_cached_hf_modules
  133. init_cached_hf_modules()
  134. # Setup OpenMP threads affinity.
  135. omp_cpuids = APHRODITE_CPU_OMP_THREADS_BIND
  136. if omp_cpuids == "all":
  137. self.local_omp_cpuid = "all"
  138. else:
  139. self.local_omp_cpuid = omp_cpuids.split("|")[rank]
  140. self.model_runner: CPUModelRunner = CPUModelRunner(
  141. model_config,
  142. parallel_config,
  143. scheduler_config,
  144. device_config,
  145. cache_config,
  146. load_config=self.load_config,
  147. lora_config=self.lora_config,
  148. kv_cache_dtype=kv_cache_dtype,
  149. prompt_adapter_config=self.prompt_adapter_config,
  150. is_driver_worker=is_driver_worker)
  151. # Uninitialized cache engine. Will be initialized by
  152. # initialize_cache.
  153. self.cache_engine: List[CPUCacheEngine]
  154. self.cpu_cache: List[List[torch.Tensor]]
  155. def init_device(self) -> None:
  156. if self.local_omp_cpuid != "all":
  157. torch.ops._C_utils.init_cpu_threads_env(self.local_omp_cpuid)
  158. self.init_distributed_environment()
  159. # Set random seed.
  160. set_random_seed(self.model_config.seed)
  161. def load_model(self):
  162. self.model_runner.load_model()
  163. def determine_num_available_blocks(self) -> Tuple[int, int]:
  164. """Determine the number of blocks available for the KV cache.
  165. This determines how many KV blocks can fit into the configured CPU
  166. KV cache space.
  167. Note that since Aphrodite assumes a block resides on GPU if it can be
  168. modified, we return num_gpu_blocks=num_cpu_blocks and num_cpu_blocks=0.
  169. This allows us to reuse the scheduler of Aphrodite without generalizing
  170. it to different devices.
  171. """
  172. # For CPU device, the block number will be calculated based on the
  173. # cpu_kvcache_space.
  174. cache_block_size = self.get_cache_block_size_bytes()
  175. num_cpu_blocks = int(self.cache_config.cpu_kvcache_space_bytes //
  176. cache_block_size)
  177. num_cpu_blocks = max(num_cpu_blocks, 0)
  178. # NOTE: To reuse the cache management procedure,
  179. # use cpu cache as 'gpu cache'.
  180. num_gpu_blocks = num_cpu_blocks
  181. num_cpu_blocks = 0
  182. return num_gpu_blocks, num_cpu_blocks
  183. def initialize_cache(self, num_gpu_blocks: int,
  184. num_cpu_blocks: int) -> None:
  185. """Initialize the KV cache. Currently, swappable CPU memory is not
  186. supported.
  187. Since this worker does not support GPUs, we use the num_gpu_blocks to
  188. determine how many non-swappable CPU blocks to allocate.
  189. """
  190. assert (num_cpu_blocks == 0
  191. ), f"{type(self)} does not support swappable cache"
  192. # NOTE: To reuse the cache management procedure,
  193. # use cpu cache as 'gpu cache'.
  194. num_cpu_blocks = num_gpu_blocks
  195. self._validate_num_cpu_blocks(num_cpu_blocks)
  196. self.cache_config.num_gpu_blocks = num_cpu_blocks
  197. self.cache_config.num_cpu_blocks = 0
  198. # Initialize the cache.
  199. self._init_cache_engine()
  200. def _validate_num_cpu_blocks(self, num_cpu_blocks: int) -> None:
  201. """Raise errors if the num_cpu_blocks is invalid.
  202. """
  203. if num_cpu_blocks <= 0:
  204. raise ValueError(
  205. "No available memory for the cache blocks. "
  206. "Try increasing `APHRODITE_CPU_KVCACHE_SPACE` when "
  207. "initializing the engine.")
  208. max_seq_len = self.cache_config.block_size * num_cpu_blocks
  209. if self.model_config.max_model_len > max_seq_len:
  210. raise ValueError(
  211. f"The model's max seq len ({self.model_config.max_model_len}) "
  212. "is larger than the maximum number of tokens that can be "
  213. f"stored in KV cache ({max_seq_len}). Try increasing "
  214. "`APHRODITE_CPU_KVCACHE_SPACE` or decreasing `max_model_len` "
  215. "when initializing the engine.")
  216. def _init_cache_engine(self) -> None:
  217. self.cache_engine = [
  218. CPUCacheEngine(self.cache_config, self.model_config,
  219. self.parallel_config, self.device_config)
  220. for _ in range(self.parallel_config.pipeline_parallel_size)
  221. ]
  222. self.cpu_cache = [
  223. self.cache_engine[ve].cpu_cache
  224. for ve in range(self.parallel_config.pipeline_parallel_size)
  225. ]
  226. self.model_runner.block_size = self.cache_engine[0].block_size
  227. assert all(
  228. self.cpu_cache[ve] is not None
  229. for ve in range(self.parallel_config.pipeline_parallel_size))
  230. # Populate the cache to warmup the memory
  231. for ve in range(self.parallel_config.pipeline_parallel_size):
  232. for layer_cache in self.cpu_cache[ve]:
  233. layer_cache.fill_(0)
  234. @property
  235. def do_metadata_broadcast(self) -> bool:
  236. return self.parallel_config.tensor_parallel_size > 1
  237. @property
  238. def kv_cache(self) -> Optional[List[List[torch.Tensor]]]:
  239. return self.cpu_cache
  240. def execute_worker(
  241. self,
  242. worker_input: WorkerInput,
  243. ) -> None:
  244. if (worker_input.blocks_to_copy is not None
  245. and worker_input.blocks_to_copy.numel() > 0):
  246. self.cache_engine[worker_input.virtual_engine].copy(
  247. worker_input.blocks_to_copy)
  248. @torch.inference_mode()
  249. def prepare_worker_input(
  250. self, execute_model_req: ExecuteModelRequest) -> WorkerInput:
  251. assert execute_model_req is not None
  252. virtual_engine = execute_model_req.virtual_engine
  253. num_seq_groups: int = len(execute_model_req.seq_group_metadata_list)
  254. blocks_to_copy = execute_model_req.blocks_to_copy
  255. blocks_to_copy = torch.tensor(execute_model_req.blocks_to_copy,
  256. device="cpu",
  257. dtype=torch.int64).view(-1, 2)
  258. assert len(execute_model_req.blocks_to_swap_in) == 0
  259. assert len(execute_model_req.blocks_to_swap_out) == 0
  260. return WorkerInput(
  261. num_seq_groups=num_seq_groups,
  262. blocks_to_copy=blocks_to_copy,
  263. virtual_engine=virtual_engine,
  264. )
  265. def init_distributed_environment(self) -> None:
  266. """Initialize the distributed environment."""
  267. parallel_config = self.parallel_config
  268. rank = self.rank
  269. distributed_init_method = self.distributed_init_method
  270. init_distributed_environment(
  271. world_size=parallel_config.world_size,
  272. rank=rank,
  273. distributed_init_method=distributed_init_method,
  274. backend="gloo",
  275. )
  276. # A small all_reduce for warmup.
  277. torch.distributed.all_reduce(torch.zeros(1).cpu())
  278. ensure_model_parallel_initialized(
  279. parallel_config.tensor_parallel_size,
  280. parallel_config.pipeline_parallel_size)
  281. def get_cache_block_size_bytes(self) -> int:
  282. """Return the size in bytes of a single KV cache block.
  283. """
  284. return CPUCacheEngine.get_cache_block_size(
  285. self.cache_config.block_size, self.cache_config.cache_dtype,
  286. self.model_config, self.parallel_config)