block_manager_v2.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. """A block manager that manages token blocks."""
  2. from itertools import chain
  3. from typing import Dict, List, Optional
  4. from typing import Sequence as GenericSequence
  5. from typing import Tuple
  6. from aphrodite.common.sequence import Sequence, SequenceGroup, SequenceStatus
  7. from aphrodite.common.utils import Device
  8. from aphrodite.processing.block.block_table import BlockTable
  9. from aphrodite.processing.block.cpu_gpu_block_allocator import (
  10. CpuGpuBlockAllocator)
  11. from aphrodite.processing.block.interfaces import Block
  12. from aphrodite.processing.block.prefix_caching_block import (
  13. ComputedBlocksTracker, LastAccessBlocksTracker)
  14. from aphrodite.processing.block.utils import (
  15. check_no_caching_or_swa_for_blockmgr_encdec)
  16. from aphrodite.processing.interfaces import AllocStatus, BlockSpaceManager
  17. SeqId = int
  18. NegativeSeqId = str
  19. EncoderSeqId = str
  20. class BlockSpaceManagerV2(BlockSpaceManager):
  21. """BlockSpaceManager which manages the allocation of KV cache.
  22. It owns responsibility for allocation, swapping, allocating memory for
  23. autoregressively-generated tokens, and other advanced features such as
  24. prefix caching, forking/copy-on-write, and sliding-window memory allocation.
  25. The current implementation is partial; in particular prefix caching and
  26. sliding-window are not feature complete.
  27. Lookahead slots
  28. The block manager has the notion of a "lookahead slot". These are slots
  29. in the KV cache that are allocated for a sequence. Unlike the other
  30. allocated slots, the content of these slots is undefined -- the worker
  31. may use the memory allocations in any way.
  32. In practice, a worker could use these lookahead slots to run multiple
  33. forward passes for a single scheduler invocation. Each successive
  34. forward pass would write KV activations to the corresponding lookahead
  35. slot. This allows low inter-token latency use-cases, where the overhead
  36. of continuous batching scheduling is amortized over >1 generated tokens.
  37. Speculative decoding uses lookahead slots to store KV activations of
  38. proposal tokens.
  39. Args:
  40. block_size (int): The size of each memory block.
  41. num_gpu_blocks (int): The number of memory blocks allocated on GPU.
  42. num_cpu_blocks (int): The number of memory blocks allocated on CPU.
  43. watermark (float, optional): The threshold used for memory swapping.
  44. Defaults to 0.01.
  45. sliding_window (Optional[int], optional): The size of the sliding
  46. window. Defaults to None.
  47. enable_caching (bool, optional): Flag indicating whether caching is
  48. enabled. Defaults to False.
  49. """
  50. def __init__(
  51. self,
  52. block_size: int,
  53. num_gpu_blocks: int,
  54. num_cpu_blocks: int,
  55. watermark: float = 0.01,
  56. sliding_window: Optional[int] = None,
  57. enable_caching: bool = False,
  58. ) -> None:
  59. self.block_size = block_size
  60. self.num_total_gpu_blocks = num_gpu_blocks
  61. self.num_total_cpu_blocks = num_cpu_blocks
  62. self.sliding_window = sliding_window
  63. # max_block_sliding_window is the max number of blocks that need to be
  64. # allocated
  65. self.max_block_sliding_window = None
  66. if sliding_window is not None:
  67. # +1 here because // rounds down
  68. num_blocks = sliding_window // block_size + 1
  69. # +1 here because the last block may not be full,
  70. # and so the sequence stretches one more block at the beginning
  71. # For example, if sliding_window is 3 and block_size is 4,
  72. # we may need 2 blocks when the second block only holds 1 token.
  73. self.max_block_sliding_window = num_blocks + 1
  74. self.watermark = watermark
  75. assert watermark >= 0.0
  76. self.enable_caching = enable_caching
  77. self.watermark_blocks = int(watermark * num_gpu_blocks)
  78. self.block_allocator = CpuGpuBlockAllocator.create(
  79. allocator_type="prefix_caching" if enable_caching else "naive",
  80. num_gpu_blocks=num_gpu_blocks,
  81. num_cpu_blocks=num_cpu_blocks,
  82. block_size=block_size,
  83. )
  84. self.block_tables: Dict[SeqId, BlockTable] = {}
  85. self.negative_block_tables: Dict[NegativeSeqId, BlockTable] = {}
  86. self.cross_block_tables: Dict[EncoderSeqId, BlockTable] = {}
  87. self._computed_blocks_tracker = ComputedBlocksTracker(
  88. self.block_allocator)
  89. self._last_access_blocks_tracker = LastAccessBlocksTracker(
  90. self.block_allocator)
  91. def can_allocate(self, seq_group: SequenceGroup) -> AllocStatus:
  92. # FIXME: Here we assume that all sequences in the group share
  93. # the same prompt. This may not be true for preempted sequences.
  94. check_no_caching_or_swa_for_blockmgr_encdec(self, seq_group)
  95. seq = seq_group.get_seqs(status=SequenceStatus.WAITING)[0]
  96. num_required_blocks = BlockTable.get_num_required_blocks(
  97. seq.get_token_ids(),
  98. block_size=self.block_size,
  99. )
  100. if seq_group.is_encoder_decoder():
  101. num_required_blocks += BlockTable.get_num_required_blocks(
  102. seq_group.get_encoder_seq().get_token_ids(),
  103. block_size=self.block_size,
  104. )
  105. if seq_group.has_negative_prompt():
  106. num_required_blocks += BlockTable.get_num_required_blocks(
  107. seq_group.get_negative_seq().get_token_ids(),
  108. block_size=self.block_size)
  109. if self.max_block_sliding_window is not None:
  110. num_required_blocks = min(num_required_blocks,
  111. self.max_block_sliding_window)
  112. num_free_gpu_blocks = self.block_allocator.get_num_free_blocks(
  113. device=Device.GPU)
  114. # Use watermark to avoid frequent cache eviction.
  115. if (self.num_total_gpu_blocks - num_required_blocks <
  116. self.watermark_blocks):
  117. return AllocStatus.NEVER
  118. if num_free_gpu_blocks - num_required_blocks >= self.watermark_blocks:
  119. return AllocStatus.OK
  120. else:
  121. return AllocStatus.LATER
  122. def _allocate_sequence(self, seq: Sequence) -> BlockTable:
  123. block_table = BlockTable(
  124. block_size=self.block_size,
  125. block_allocator=self.block_allocator,
  126. max_block_sliding_window=self.max_block_sliding_window,
  127. )
  128. block_table.allocate(seq.get_token_ids())
  129. return block_table
  130. def allocate(self, seq_group: SequenceGroup) -> None:
  131. # Allocate self-attention block tables for decoder sequences
  132. waiting_seqs = seq_group.get_seqs(status=SequenceStatus.WAITING)
  133. assert not (set(seq.seq_id for seq in waiting_seqs)
  134. & self.block_tables.keys()), "block table already exists"
  135. # NOTE: Here we assume that all sequences in the group have the same
  136. # prompt.
  137. seq = waiting_seqs[0]
  138. block_table: BlockTable = self._allocate_sequence(seq)
  139. self.block_tables[seq.seq_id] = block_table
  140. # Track seq
  141. self._computed_blocks_tracker.add_seq(seq.seq_id)
  142. self._last_access_blocks_tracker.add_seq(seq.seq_id)
  143. # Assign the block table for each sequence.
  144. for seq in waiting_seqs[1:]:
  145. self.block_tables[seq.seq_id] = block_table.fork()
  146. # Track seq
  147. self._computed_blocks_tracker.add_seq(seq.seq_id)
  148. self._last_access_blocks_tracker.add_seq(seq.seq_id)
  149. # Allocate cross-attention block table for encoder sequence
  150. #
  151. # NOTE: Here we assume that all sequences in the group have the same
  152. # encoder prompt.
  153. request_id = seq_group.request_id
  154. assert (request_id
  155. not in self.cross_block_tables), \
  156. "block table already exists"
  157. assert (request_id
  158. not in self.negative_block_tables), \
  159. "block table already exists"
  160. if seq_group.has_negative_prompt():
  161. block_table = self._allocate_sequence(
  162. seq_group.get_negative_seq())
  163. self.negative_block_tables[request_id] = block_table
  164. check_no_caching_or_swa_for_blockmgr_encdec(self, seq_group)
  165. if seq_group.is_encoder_decoder():
  166. block_table = self._allocate_sequence(seq_group.get_encoder_seq())
  167. self.cross_block_tables[request_id] = block_table
  168. def can_append_slots(self, seq_group: SequenceGroup,
  169. num_lookahead_slots: int) -> bool:
  170. """Determine if there is enough space in the GPU KV cache to continue
  171. generation of the specified sequence group.
  172. We use a worst-case heuristic: assume each touched block will require a
  173. new allocation (either via CoW or new block). We can append slots if the
  174. number of touched blocks is less than the number of free blocks.
  175. "Lookahead slots" are slots that are allocated in addition to the slots
  176. for known tokens. The contents of the lookahead slots are not defined.
  177. This is used by speculative decoding when speculating future tokens.
  178. """
  179. num_touched_blocks = 0
  180. for seq in seq_group.get_seqs(status=SequenceStatus.RUNNING):
  181. block_table = self.block_tables[seq.seq_id]
  182. num_touched_blocks += (
  183. block_table.get_num_blocks_touched_by_append_slots(
  184. token_ids=block_table.get_unseen_token_ids(
  185. seq.get_token_ids()),
  186. num_lookahead_slots=num_lookahead_slots,
  187. ))
  188. negative_block_table = self.negative_block_tables[
  189. seq_group.request_id]
  190. num_touched_blocks += (
  191. negative_block_table.get_num_blocks_touched_by_append_slots(
  192. token_ids=negative_block_table.get_unseen_token_ids(
  193. seq_group.get_negative_seq().get_token_ids()),
  194. num_lookahead_slots=num_lookahead_slots,
  195. ))
  196. num_free_gpu_blocks = self.block_allocator.get_num_free_blocks(
  197. Device.GPU)
  198. return num_touched_blocks <= num_free_gpu_blocks
  199. def append_slots(
  200. self,
  201. seq: Sequence,
  202. num_lookahead_slots: int,
  203. seq_group: SequenceGroup,
  204. ) -> List[Tuple[int, int]]:
  205. block_table = self.block_tables[seq.seq_id]
  206. block_table.append_token_ids(
  207. token_ids=block_table.get_unseen_token_ids(seq.get_token_ids()),
  208. num_lookahead_slots=num_lookahead_slots,
  209. num_computed_slots=seq.data.get_num_computed_tokens(),
  210. )
  211. negative_block_table = self.negative_block_tables[seq_group.request_id]
  212. negative_seq = seq_group.negative_seq
  213. negative_block_table.append_token_ids(
  214. token_ids=negative_block_table.get_unseen_token_ids(
  215. negative_seq.get_token_ids()),
  216. num_lookahead_slots=num_lookahead_slots,
  217. num_computed_slots=negative_seq.data.get_num_computed_tokens(),
  218. )
  219. # Return any new copy-on-writes.
  220. new_cows = self.block_allocator.clear_copy_on_writes()
  221. return new_cows
  222. def free(self, seq: Sequence) -> None:
  223. seq_id = seq.seq_id
  224. if seq_id not in self.block_tables:
  225. # Already freed or haven't been scheduled yet.
  226. return
  227. # Update seq block ids with the latest access time
  228. self._last_access_blocks_tracker.update_seq_blocks_last_access(
  229. seq_id, self.block_tables[seq.seq_id].physical_block_ids)
  230. # Untrack seq
  231. self._last_access_blocks_tracker.remove_seq(seq_id)
  232. self._computed_blocks_tracker.remove_seq(seq_id)
  233. # Free table/blocks
  234. self.block_tables[seq_id].free()
  235. del self.block_tables[seq_id]
  236. def free_cross(self, seq_group: SequenceGroup) -> None:
  237. request_id = seq_group.request_id
  238. if request_id not in self.cross_block_tables:
  239. # Already freed or hasn't been scheduled yet.
  240. return
  241. self.cross_block_tables[request_id].free()
  242. del self.cross_block_tables[request_id]
  243. def free_negative(self, seq_group: SequenceGroup) -> None:
  244. request_id = seq_group.request_id
  245. if request_id not in self.negative_block_tables:
  246. return
  247. self.negative_block_tables[request_id].free()
  248. del self.negative_block_tables[request_id]
  249. def get_block_table(self, seq: Sequence) -> List[int]:
  250. block_ids = self.block_tables[seq.seq_id].physical_block_ids
  251. return block_ids # type: ignore
  252. def get_cross_block_table(self, seq_group: SequenceGroup) -> List[int]:
  253. request_id = seq_group.request_id
  254. assert request_id in self.cross_block_tables
  255. block_ids = self.cross_block_tables[request_id].physical_block_ids
  256. assert all(b is not None for b in block_ids)
  257. return block_ids # type: ignore
  258. def get_negative_block_table(self, seq_group: SequenceGroup) -> List[int]:
  259. request_id = seq_group.request_id
  260. assert request_id in self.negative_block_tables
  261. block_ids = self.negative_block_tables[request_id].physical_block_ids
  262. assert all(b is not None for b in block_ids)
  263. return block_ids
  264. def access_all_blocks_in_seq(self, seq: Sequence, now: float):
  265. if self.enable_caching:
  266. # Record the latest access time for the sequence. The actual update
  267. # of the block ids is deferred to the sequence free(..) call, since
  268. # only during freeing of block ids, the blocks are actually added to
  269. # the evictor (which is when the most updated time is required)
  270. # (This avoids expensive calls to mark_blocks_as_accessed(..))
  271. self._last_access_blocks_tracker.update_last_access(
  272. seq.seq_id, now)
  273. def mark_blocks_as_computed(self, seq_group: SequenceGroup):
  274. # The only need for mark block as computed is for prefix caching,
  275. # while currently we could determine whether one block is computed
  276. # or not by check whether it has content hash.
  277. # So this function is useless for block_v2.
  278. pass
  279. def get_common_computed_block_ids(
  280. self, seqs: List[Sequence]) -> GenericSequence[int]:
  281. """Determine which blocks for which we skip prefill.
  282. With prefix caching we can skip prefill for previously-generated blocks.
  283. Currently, the attention implementation only supports skipping cached
  284. blocks if they are a contiguous prefix of cached blocks.
  285. This method determines which blocks can be safely skipped for all
  286. sequences in the sequence group.
  287. """
  288. computed_seq_block_ids = []
  289. for seq in seqs:
  290. computed_seq_block_ids.append(
  291. self._computed_blocks_tracker.
  292. get_cached_computed_blocks_and_update(
  293. seq.seq_id,
  294. self.block_tables[seq.seq_id].physical_block_ids))
  295. # NOTE: This assumes seq_block_ids doesn't contain any None.
  296. return self.block_allocator.get_common_computed_block_ids(
  297. computed_seq_block_ids) # type: ignore
  298. def fork(self, parent_seq: Sequence, child_seq: Sequence) -> None:
  299. if parent_seq.seq_id not in self.block_tables:
  300. # Parent sequence has either been freed or never existed.
  301. return
  302. src_block_table = self.block_tables[parent_seq.seq_id]
  303. self.block_tables[child_seq.seq_id] = src_block_table.fork()
  304. # Track child seq
  305. self._computed_blocks_tracker.add_seq(child_seq.seq_id)
  306. self._last_access_blocks_tracker.add_seq(child_seq.seq_id)
  307. def can_swap_in(self, seq_group: SequenceGroup,
  308. num_lookahead_slots: int) -> AllocStatus:
  309. """Returns the AllocStatus for the given sequence_group
  310. with num_lookahead_slots.
  311. Args:
  312. sequence_group (SequenceGroup): The sequence group to swap in.
  313. num_lookahead_slots (int): Number of lookahead slots used in
  314. speculative decoding, default to 0.
  315. Returns:
  316. AllocStatus: The AllocStatus for the given sequence group.
  317. """
  318. return self._can_swap(seq_group, Device.GPU, SequenceStatus.SWAPPED,
  319. num_lookahead_slots)
  320. def swap_in(self, seq_group: SequenceGroup) -> List[Tuple[int, int]]:
  321. """Returns the block id mapping (from CPU to GPU) generated by
  322. swapping in the given seq_group with num_lookahead_slots.
  323. Args:
  324. seq_group (SequenceGroup): The sequence group to swap in.
  325. Returns:
  326. List[Tuple[int, int]]: The mapping of swapping block from CPU
  327. to GPU.
  328. """
  329. physical_block_id_mapping = []
  330. for seq in seq_group.get_seqs(status=SequenceStatus.SWAPPED):
  331. blocks = self.block_tables[seq.seq_id].blocks
  332. if len(blocks) == 0:
  333. continue
  334. seq_swap_mapping = self.block_allocator.swap(blocks=blocks,
  335. src_device=Device.CPU,
  336. dst_device=Device.GPU)
  337. # Refresh the block ids of the table (post-swap)
  338. self.block_tables[seq.seq_id].update(blocks)
  339. seq_physical_block_id_mapping = {
  340. self.block_allocator.get_physical_block_id(
  341. Device.CPU, cpu_block_id):
  342. self.block_allocator.get_physical_block_id(
  343. Device.GPU, gpu_block_id)
  344. for cpu_block_id, gpu_block_id in seq_swap_mapping.items()
  345. }
  346. physical_block_id_mapping.extend(
  347. list(seq_physical_block_id_mapping.items()))
  348. return physical_block_id_mapping
  349. def can_swap_out(self, seq_group: SequenceGroup) -> bool:
  350. """Returns whether we can swap out the given sequence_group
  351. with num_lookahead_slots.
  352. Args:
  353. seq_group (SequenceGroup): The sequence group to swap in.
  354. num_lookahead_slots (int): Number of lookahead slots used in
  355. speculative decoding, default to 0.
  356. Returns:
  357. bool: Whether it's possible to swap out current sequence group.
  358. """
  359. alloc_status = self._can_swap(seq_group, Device.CPU,
  360. SequenceStatus.RUNNING)
  361. if alloc_status == AllocStatus.OK:
  362. return True
  363. return False
  364. def swap_out(self, seq_group: SequenceGroup) -> List[Tuple[int, int]]:
  365. """Returns the block id mapping (from GPU to CPU) generated by
  366. swapping out the given sequence_group with num_lookahead_slots.
  367. Args:
  368. sequence_group (SequenceGroup): The sequence group to swap in.
  369. Returns:
  370. List[Tuple[int, int]]: The mapping of swapping block from
  371. GPU to CPU.
  372. """
  373. physical_block_id_mapping = []
  374. for seq in seq_group.get_seqs(status=SequenceStatus.RUNNING):
  375. blocks = self.block_tables[seq.seq_id].blocks
  376. if len(blocks) == 0:
  377. continue
  378. seq_swap_mapping = self.block_allocator.swap(blocks=blocks,
  379. src_device=Device.GPU,
  380. dst_device=Device.CPU)
  381. # Refresh the block ids of the table (post-swap)
  382. self.block_tables[seq.seq_id].update(blocks)
  383. seq_physical_block_id_mapping = {
  384. self.block_allocator.get_physical_block_id(
  385. Device.GPU, gpu_block_id):
  386. self.block_allocator.get_physical_block_id(
  387. Device.CPU, cpu_block_id)
  388. for gpu_block_id, cpu_block_id in seq_swap_mapping.items()
  389. }
  390. physical_block_id_mapping.extend(
  391. list(seq_physical_block_id_mapping.items()))
  392. return physical_block_id_mapping
  393. def get_num_free_gpu_blocks(self) -> int:
  394. return self.block_allocator.get_num_free_blocks(Device.GPU)
  395. def get_num_free_cpu_blocks(self) -> int:
  396. return self.block_allocator.get_num_free_blocks(Device.CPU)
  397. def get_prefix_cache_hit_rate(self, device: Device) -> float:
  398. return self.block_allocator.get_prefix_cache_hit_rate(device)
  399. def _can_swap(self,
  400. seq_group: SequenceGroup,
  401. device: Device,
  402. status: SequenceStatus,
  403. num_lookahead_slots: int = 0) -> AllocStatus:
  404. """Returns the AllocStatus for swapping in/out the given sequence_group
  405. on to the 'device'.
  406. Args:
  407. sequence_group (SequenceGroup): The sequence group to swap in.
  408. device (Device): device to swap the 'seq_group' on.
  409. status (SequenceStatus): The status of sequence which is needed
  410. for action. RUNNING for swap out and SWAPPED for swap in
  411. num_lookahead_slots (int): Number of lookahead slots used in
  412. speculative decoding, default to 0.
  413. Returns:
  414. AllocStatus: The AllocStatus for swapping in/out the given
  415. sequence_group on to the 'device'.
  416. """
  417. blocks = self._get_blocks_for_swap(seq_group, status)
  418. num_blocks_touched = self.block_allocator.get_num_blocks_touched(
  419. blocks, device, num_lookahead_slots)
  420. watermark_blocks = 0
  421. if device == Device.GPU:
  422. watermark_blocks = self.watermark_blocks
  423. if self.block_allocator.get_num_total_blocks(
  424. device) < num_blocks_touched:
  425. return AllocStatus.NEVER
  426. elif self.block_allocator.get_num_free_blocks(
  427. device) - num_blocks_touched >= watermark_blocks:
  428. return AllocStatus.OK
  429. else:
  430. return AllocStatus.LATER
  431. def _get_blocks_for_swap(self, seq_group: SequenceGroup,
  432. status: SequenceStatus) -> List[Block]:
  433. """Returns the list of blocks those are touched by the seq_group
  434. Args:
  435. sequence_group (SequenceGroup): The sequence group to swap in.
  436. status (SequenceStatus): The status of sequence which is needed
  437. for action. RUNNING for swap out and SWAPPED for swap in
  438. Returns:
  439. The list of blocks those are touched by the seq_group.
  440. """
  441. blocks: Dict[int, List[Block]] = {}
  442. for seq in seq_group.get_seqs(status=status):
  443. block_table = self.block_tables[seq.seq_id]
  444. if block_table.blocks is not None:
  445. blocks[seq.seq_id] = block_table.blocks
  446. combined_blocks = list(chain(*blocks.values()))
  447. return combined_blocks