block_manager.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. """A block manager that manages token blocks."""
  2. import enum
  3. from typing import Dict, List, Optional, Set, Tuple
  4. from aphrodite.common.block import BlockTable, PhysicalTokenBlock
  5. from aphrodite.common.sequence import Sequence, SequenceGroup, SequenceStatus
  6. from aphrodite.common.utils import Device
  7. class BlockAllocator:
  8. """Manages free physical token blocks for a device.
  9. The allocator maintains a list of free blocks and allocates a block when
  10. requested. When a block is freed, its reference count is decremented. If
  11. the reference count becomes zero, the block is added back to the free list.
  12. """
  13. def __init__(
  14. self,
  15. device: Device,
  16. block_size: int,
  17. num_blocks: int,
  18. ) -> None:
  19. self.device = device
  20. self.block_size = block_size
  21. self.num_blocks = num_blocks
  22. # Initialize the free blocks.
  23. self.free_blocks: BlockTable = []
  24. for i in range(num_blocks):
  25. block = PhysicalTokenBlock(device=device,
  26. block_number=i,
  27. block_size=block_size)
  28. self.free_blocks.append(block)
  29. def allocate(self) -> PhysicalTokenBlock:
  30. if not self.free_blocks:
  31. raise ValueError("Out of memory! No free blocks are available.")
  32. block = self.free_blocks.pop()
  33. block.ref_count = 1
  34. return block
  35. def free(self, block: PhysicalTokenBlock) -> None:
  36. if block.ref_count == 0:
  37. raise ValueError(f"Double free! {block} is already freed.")
  38. block.ref_count -= 1
  39. if block.ref_count == 0:
  40. self.free_blocks.append(block)
  41. def get_num_free_blocks(self) -> int:
  42. return len(self.free_blocks)
  43. class AllocStatus(enum.Enum):
  44. """Result for BlockSpaceManager.can_allocate
  45. 1. OK: seq_group can be allocated now.
  46. 2. LATER: seq_group cannot be allocated.
  47. The capacity of allocator is larger than seq_group required.
  48. 3. NEVER: seq_group can never be allocated.
  49. The seq_group is too large to allocated in GPU.
  50. """
  51. OK = enum.auto()
  52. LATER = enum.auto()
  53. NEVER = enum.auto()
  54. class BlockSpaceManager:
  55. """Manages the mapping between logical and physical token blocks."""
  56. def __init__(
  57. self,
  58. block_size: int,
  59. num_gpu_blocks: int,
  60. num_cpu_blocks: int,
  61. watermark: float = 0.01,
  62. sliding_window: Optional[int] = None,
  63. ) -> None:
  64. self.block_size = block_size
  65. self.num_total_gpu_blocks = num_gpu_blocks
  66. self.num_total_cpu_blocks = num_cpu_blocks
  67. self.block_sliding_window = None
  68. if sliding_window is not None:
  69. assert sliding_window % block_size == 0, (sliding_window,
  70. block_size)
  71. self.block_sliding_window = sliding_window // block_size
  72. self.watermark = watermark
  73. assert watermark >= 0.0
  74. self.watermark_blocks = int(watermark * num_gpu_blocks)
  75. self.gpu_allocator = BlockAllocator(Device.GPU, block_size,
  76. num_gpu_blocks)
  77. self.cpu_allocator = BlockAllocator(Device.CPU, block_size,
  78. num_cpu_blocks)
  79. # Mapping: seq_id -> BlockTable.
  80. self.block_tables: Dict[int, BlockTable] = {}
  81. def can_allocate(self, seq_group: SequenceGroup) -> AllocStatus:
  82. # FIXME: Here we assume that all sequences in the group share
  83. # the same prompt. This may not be true for preempted sequences.
  84. seq = seq_group.get_seqs(status=SequenceStatus.WAITING)[0]
  85. num_required_blocks = len(seq.logical_token_blocks)
  86. if seq_group.prefix is not None and seq_group.prefix.allocated:
  87. num_required_blocks -= seq_group.prefix.get_num_blocks()
  88. if self.block_sliding_window is not None:
  89. num_required_blocks = min(num_required_blocks,
  90. self.block_sliding_window)
  91. num_free_gpu_blocks = self.gpu_allocator.get_num_free_blocks()
  92. # Use watermark to avoid frequent cache eviction.
  93. if (self.num_total_gpu_blocks - num_required_blocks <
  94. self.watermark_blocks):
  95. return AllocStatus.NEVER
  96. if num_free_gpu_blocks - num_required_blocks >= self.watermark_blocks:
  97. return AllocStatus.OK
  98. else:
  99. return AllocStatus.LATER
  100. def allocate(self, seq_group: SequenceGroup) -> None:
  101. # NOTE: Here we assume that all sequences in the group have the same
  102. # prompt.
  103. seq = seq_group.get_seqs(status=SequenceStatus.WAITING)[0]
  104. # Allocate new physical token blocks that will store the prompt tokens.
  105. num_prompt_blocks = len(seq.logical_token_blocks)
  106. block_table: BlockTable = []
  107. prefix_block_table: BlockTable = []
  108. num_prefix_blocks = 0
  109. prefix = seq_group.prefix
  110. if prefix is not None and prefix.allocated:
  111. # Prefix has already been allocated. Use the existing block table.
  112. num_prompt_blocks -= prefix.get_num_blocks()
  113. for block in prefix.block_table:
  114. block.ref_count += seq_group.num_seqs()
  115. block_table.append(block)
  116. for logical_idx in range(num_prompt_blocks):
  117. if (self.block_sliding_window is not None
  118. and logical_idx >= self.block_sliding_window):
  119. block = block_table[logical_idx % self.block_sliding_window]
  120. else:
  121. block = self.gpu_allocator.allocate()
  122. # Set the reference counts of the token blocks.
  123. block.ref_count = seq_group.num_seqs()
  124. block_table.append(block)
  125. if prefix is not None and not prefix.allocated:
  126. # Allocate blocks for the prefix, we will compute the prefix's
  127. # KV cache in this run.
  128. num_prefix_blocks = prefix.get_num_blocks()
  129. prefix_block_table = block_table[:num_prefix_blocks]
  130. for block in prefix_block_table:
  131. block.ref_count += 1
  132. prefix.set_block_table(prefix_block_table)
  133. # Assign the block table for each sequence.
  134. for seq in seq_group.get_seqs(status=SequenceStatus.WAITING):
  135. self.block_tables[seq.seq_id] = block_table.copy()
  136. def can_append_slot(self, seq_group: SequenceGroup) -> bool:
  137. # Simple heuristic: If there is at least one free block
  138. # for each sequence, we can append.
  139. num_free_gpu_blocks = self.gpu_allocator.get_num_free_blocks()
  140. num_seqs = seq_group.num_seqs(status=SequenceStatus.RUNNING)
  141. return num_seqs <= num_free_gpu_blocks
  142. def append_slot(self, seq: Sequence) -> Optional[Tuple[int, int]]:
  143. """Allocate a physical slot for a new token."""
  144. logical_blocks = seq.logical_token_blocks
  145. block_table = self.block_tables[seq.seq_id]
  146. if len(block_table) < len(logical_blocks):
  147. if (self.block_sliding_window
  148. and len(block_table) >= self.block_sliding_window):
  149. # re-use a block
  150. block_table.append(block_table[len(block_table) %
  151. self.block_sliding_window])
  152. else:
  153. # The sequence has a new logical block.
  154. # Allocate a new physical block.
  155. block = self.gpu_allocator.allocate()
  156. block_table.append(block)
  157. return None
  158. # We want to append the token to the last physical block.
  159. last_block = block_table[-1]
  160. assert last_block.device == Device.GPU
  161. if last_block.ref_count == 1:
  162. # Not shared with other sequences. Appendable.
  163. return None
  164. else:
  165. # The last block is shared with other sequences.
  166. # Copy on Write: Allocate a new block and copy the tokens.
  167. new_block = self.gpu_allocator.allocate()
  168. block_table[-1] = new_block
  169. self.gpu_allocator.free(last_block)
  170. return last_block.block_number, new_block.block_number
  171. def fork(self, parent_seq: Sequence, child_seq: Sequence) -> None:
  172. # NOTE: fork does not allocate a new physical block.
  173. # Thus, it is always safe from OOM.
  174. src_block_table = self.block_tables[parent_seq.seq_id]
  175. self.block_tables[child_seq.seq_id] = src_block_table.copy()
  176. for block in src_block_table:
  177. block.ref_count += 1
  178. def _get_physical_blocks(
  179. self, seq_group: SequenceGroup) -> List[PhysicalTokenBlock]:
  180. # NOTE: Here, we assume that the physical blocks are only shared by
  181. # the sequences in the same group.
  182. blocks: Set[PhysicalTokenBlock] = set()
  183. for seq in seq_group.get_seqs():
  184. if seq.is_finished():
  185. continue
  186. blocks.update(self.block_tables[seq.seq_id])
  187. return list(blocks)
  188. def can_swap_in(self, seq_group: SequenceGroup) -> bool:
  189. blocks = self._get_physical_blocks(seq_group)
  190. num_swapped_seqs = seq_group.num_seqs(status=SequenceStatus.SWAPPED)
  191. num_free_blocks = self.gpu_allocator.get_num_free_blocks()
  192. # NOTE: Conservatively, we assume that every sequence will allocate
  193. # at least one free block right after the swap-in.
  194. # NOTE: This should match the logic in can_append_slot().
  195. num_required_blocks = len(blocks) + num_swapped_seqs
  196. return num_free_blocks - num_required_blocks >= self.watermark_blocks
  197. def swap_in(self, seq_group: SequenceGroup) -> Dict[int, int]:
  198. # CPU block -> GPU block.
  199. if seq_group.prefix is not None:
  200. # make sure to swap in the prefix first
  201. assert seq_group.prefix.allocated and seq_group.prefix.computed
  202. mapping: Dict[PhysicalTokenBlock, PhysicalTokenBlock] = {}
  203. for seq in seq_group.get_seqs(status=SequenceStatus.SWAPPED):
  204. new_block_table: BlockTable = []
  205. block_table = self.block_tables[seq.seq_id]
  206. if seq_group.prefix is not None:
  207. for block in seq_group.prefix.block_table:
  208. new_block_table.append(block)
  209. block.ref_count += 1
  210. for cpu_block in block_table:
  211. if cpu_block in mapping:
  212. gpu_block = mapping[cpu_block]
  213. gpu_block.ref_count += 1
  214. else:
  215. gpu_block = self.gpu_allocator.allocate()
  216. mapping[cpu_block] = gpu_block
  217. new_block_table.append(gpu_block)
  218. # Free the CPU block swapped in to GPU.
  219. self.cpu_allocator.free(cpu_block)
  220. self.block_tables[seq.seq_id] = new_block_table
  221. block_number_mapping = {
  222. cpu_block.block_number: gpu_block.block_number
  223. for cpu_block, gpu_block in mapping.items()
  224. }
  225. return block_number_mapping
  226. def can_swap_out(self, seq_group: SequenceGroup) -> bool:
  227. blocks = self._get_physical_blocks(seq_group)
  228. return len(blocks) <= self.cpu_allocator.get_num_free_blocks()
  229. def swap_out(self, seq_group: SequenceGroup) -> Dict[int, int]:
  230. # GPU block -> CPU block.
  231. mapping: Dict[PhysicalTokenBlock, PhysicalTokenBlock] = {}
  232. for seq in seq_group.get_seqs(status=SequenceStatus.RUNNING):
  233. new_block_table: BlockTable = []
  234. block_table = self.block_tables[seq.seq_id]
  235. for gpu_block in block_table:
  236. if (seq_group.prefix is not None
  237. and gpu_block in seq_group.prefix.block_table):
  238. # NOTE: We do not swap out the prefix blocks for now.
  239. self.gpu_allocator.free(gpu_block)
  240. continue
  241. if gpu_block in mapping:
  242. cpu_block = mapping[gpu_block]
  243. cpu_block.ref_count += 1
  244. else:
  245. cpu_block = self.cpu_allocator.allocate()
  246. mapping[gpu_block] = cpu_block
  247. new_block_table.append(cpu_block)
  248. # Free the GPU block swapped out to CPU.
  249. self.gpu_allocator.free(gpu_block)
  250. self.block_tables[seq.seq_id] = new_block_table
  251. block_number_mapping = {
  252. gpu_block.block_number: cpu_block.block_number
  253. for gpu_block, cpu_block in mapping.items()
  254. }
  255. return block_number_mapping
  256. def _free_block_table(self, block_table: BlockTable) -> None:
  257. for block in set(block_table):
  258. if block.device == Device.GPU:
  259. self.gpu_allocator.free(block)
  260. else:
  261. self.cpu_allocator.free(block)
  262. def free(self, seq: Sequence) -> None:
  263. if seq.seq_id not in self.block_tables:
  264. # Already freed or haven't been scheduled yet.
  265. return
  266. block_table = self.block_tables[seq.seq_id]
  267. self._free_block_table(block_table)
  268. del self.block_tables[seq.seq_id]
  269. def reset(self) -> None:
  270. for block_table in self.block_tables.values():
  271. self._free_block_table(block_table)
  272. self.block_tables.clear()
  273. def get_block_table(self, seq: Sequence) -> List[int]:
  274. block_table = self.block_tables[seq.seq_id]
  275. return [block.block_number for block in block_table]
  276. def get_num_free_gpu_blocks(self) -> int:
  277. return self.gpu_allocator.get_num_free_blocks()
  278. def get_num_free_cpu_blocks(self) -> int:
  279. return self.cpu_allocator.get_num_free_blocks()