block_manager.py 10 KB

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