block_manager_v1.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  1. """A block manager that manages token blocks."""
  2. import math
  3. from abc import ABC, abstractmethod
  4. from itertools import count, takewhile
  5. from os.path import commonprefix
  6. from typing import Dict, List, Optional
  7. from typing import Sequence as GenericSequence
  8. from typing import Set, Tuple
  9. from loguru import logger
  10. from aphrodite.common.block import BlockTable, PhysicalTokenBlock
  11. from aphrodite.common.sequence import Sequence, SequenceGroup, SequenceStatus
  12. from aphrodite.common.utils import Device
  13. from aphrodite.processing.block.utils import \
  14. check_no_caching_or_swa_for_blockmgr_encdec
  15. from aphrodite.processing.evictor_v1 import (EvictionPolicy, Evictor,
  16. make_evictor)
  17. from aphrodite.processing.interfaces import AllocStatus, BlockSpaceManager
  18. class BlockAllocatorBase(ABC):
  19. """Manages free physical token blocks for a device.
  20. The allocator maintains a list of free blocks and allocates a block when
  21. requested. When a block is freed, its reference count is decremented. If
  22. the reference count becomes zero, the block is added back to the free list.
  23. """
  24. @abstractmethod
  25. def __init__(self,
  26. device: Device,
  27. block_size: int,
  28. num_blocks: int,
  29. eviction_policy: EvictionPolicy = EvictionPolicy.LRU):
  30. pass
  31. @abstractmethod
  32. def allocate(self,
  33. block_hash: Optional[int] = None,
  34. num_hashed_tokens: int = 0) -> PhysicalTokenBlock:
  35. pass
  36. @abstractmethod
  37. def free(self, block: PhysicalTokenBlock) -> None:
  38. pass
  39. @abstractmethod
  40. def get_num_free_blocks(self) -> int:
  41. pass
  42. @abstractmethod
  43. def get_num_total_blocks(self) -> int:
  44. pass
  45. @abstractmethod
  46. def contains_block(self, block_hash: int) -> bool:
  47. pass
  48. @abstractmethod
  49. def update_hash(self, block_hash: int, block: PhysicalTokenBlock):
  50. pass
  51. class CachedBlockAllocator(BlockAllocatorBase):
  52. """Manages free physical token blocks for a device.
  53. The allocator maintains a list of free blocks and allocates a block when
  54. requested. When a block is freed, its reference count is decremented. If
  55. the reference count becomes zero, the block is added back to the free list.
  56. """
  57. def __init__(self,
  58. device: Device,
  59. block_size: int,
  60. num_blocks: int,
  61. eviction_policy: EvictionPolicy = EvictionPolicy.LRU) -> None:
  62. self.device = device
  63. self.block_size = block_size
  64. self.num_blocks = num_blocks
  65. self.current_num_blocks = 0
  66. self.cached_blocks: Dict[int, PhysicalTokenBlock] = {}
  67. self.evictor: Evictor = make_evictor(eviction_policy)
  68. self.default_hash_ctr = count()
  69. def allocate_block(self, block_hash: int,
  70. num_hashed_tokens: int) -> PhysicalTokenBlock:
  71. if self.current_num_blocks == self.num_blocks:
  72. block = self.evictor.evict()
  73. block.block_hash = block_hash
  74. block.num_hashed_tokens = num_hashed_tokens
  75. return block
  76. block = PhysicalTokenBlock(device=self.device,
  77. block_number=self.current_num_blocks,
  78. block_size=self.block_size,
  79. block_hash=block_hash,
  80. num_hashed_tokens=num_hashed_tokens)
  81. self.current_num_blocks += 1
  82. return block
  83. def allocate(self,
  84. block_hash: Optional[int] = None,
  85. num_hashed_tokens: int = 0) -> PhysicalTokenBlock:
  86. if block_hash is None:
  87. block_hash = next(self.default_hash_ctr)
  88. if block_hash in self.evictor:
  89. assert block_hash not in self.cached_blocks
  90. block = self.evictor.remove(block_hash)
  91. assert block.ref_count == 0
  92. self.cached_blocks[block_hash] = block
  93. block.ref_count += 1
  94. assert block.block_hash == block_hash
  95. return block
  96. if block_hash not in self.cached_blocks:
  97. self.cached_blocks[block_hash] = self.allocate_block(
  98. block_hash, num_hashed_tokens)
  99. block = self.cached_blocks[block_hash]
  100. assert block.block_hash == block_hash
  101. block.ref_count += 1
  102. return block
  103. def free(self, block: PhysicalTokenBlock) -> None:
  104. if block.ref_count == 0:
  105. raise ValueError(f"Double free! {block} is already freed.")
  106. block.ref_count -= 1
  107. if block.ref_count == 0:
  108. assert block.block_hash not in self.evictor
  109. self.evictor.add(block)
  110. # Remove the block from the cached_blocks
  111. del self.cached_blocks[block.block_hash]
  112. def get_num_free_blocks(self) -> int:
  113. return (self.num_blocks - self.current_num_blocks +
  114. self.evictor.num_blocks)
  115. def get_num_total_blocks(self) -> int:
  116. return self.num_blocks
  117. def contains_block(self, block_hash: int) -> bool:
  118. return block_hash in self.cached_blocks or block_hash in self.evictor
  119. def update_hash(self, block_hash: int, block: PhysicalTokenBlock):
  120. # Update the hash of block and the cached_blocks dictionary.
  121. assert not self.contains_block(block_hash)
  122. old_hash = block.block_hash
  123. block.block_hash = block_hash
  124. del self.cached_blocks[old_hash]
  125. self.cached_blocks[block_hash] = block
  126. class UncachedBlockAllocator(BlockAllocatorBase):
  127. """Manages free physical token blocks for a device.
  128. The allocator maintains a list of free blocks and allocates a block when
  129. requested. When a block is freed, its reference count is decremented. If
  130. the reference count becomes zero, the block is added back to the free list.
  131. """
  132. def __init__(
  133. self,
  134. device: Device,
  135. block_size: int,
  136. num_blocks: int,
  137. ) -> None:
  138. self.device = device
  139. self.block_size = block_size
  140. self.num_blocks = num_blocks
  141. # Initialize the free blocks.
  142. self.free_blocks: BlockTable = []
  143. for i in range(num_blocks):
  144. block = PhysicalTokenBlock(device=device,
  145. block_number=i,
  146. block_size=block_size,
  147. block_hash=-1,
  148. num_hashed_tokens=0)
  149. self.free_blocks.append(block)
  150. def allocate(self,
  151. block_hash: Optional[int] = None,
  152. num_hashed_tokens: int = 0) -> PhysicalTokenBlock:
  153. if not self.free_blocks:
  154. raise ValueError("Out of memory! No free blocks are available.")
  155. block = self.free_blocks.pop()
  156. block.ref_count = 1
  157. return block
  158. def free(self, block: PhysicalTokenBlock) -> None:
  159. if block.ref_count == 0:
  160. raise ValueError(f"Double free! {block} is already freed.")
  161. block.ref_count -= 1
  162. if block.ref_count == 0:
  163. self.free_blocks.append(block)
  164. def get_num_free_blocks(self) -> int:
  165. return len(self.free_blocks)
  166. def get_num_total_blocks(self) -> int:
  167. return self.num_blocks
  168. def contains_block(self, block_hash: int) -> bool:
  169. raise NotImplementedError(
  170. "Invalid codepath for uncached block allocator.")
  171. def update_hash(self, block_hash: int, block: PhysicalTokenBlock):
  172. raise NotImplementedError(
  173. "Invalid codepath for uncached block allocator.")
  174. class BlockSpaceManagerV1(BlockSpaceManager):
  175. """Manages the mapping between logical and physical token blocks."""
  176. def __init__(
  177. self,
  178. block_size: int,
  179. num_gpu_blocks: int,
  180. num_cpu_blocks: int,
  181. watermark: float = 0.01,
  182. sliding_window: Optional[int] = None,
  183. enable_caching: bool = False,
  184. ) -> None:
  185. self.block_size = block_size
  186. self.num_total_gpu_blocks = num_gpu_blocks
  187. self.num_total_cpu_blocks = num_cpu_blocks
  188. if enable_caching and sliding_window is not None:
  189. raise NotImplementedError(
  190. "Sliding window is not allowed with prefix caching enabled!")
  191. self.block_sliding_window = None
  192. if sliding_window is not None:
  193. # Round up to nearest block size to regularize sliding window
  194. # allocation sizes.
  195. self.block_sliding_window = math.ceil(sliding_window / block_size)
  196. self.watermark = watermark
  197. assert watermark >= 0.0
  198. self.enable_caching = enable_caching
  199. self.watermark_blocks = int(watermark * num_gpu_blocks)
  200. if self.enable_caching:
  201. logger.info("Automatic prefix caching is enabled.")
  202. self.gpu_allocator: BlockAllocatorBase = CachedBlockAllocator(
  203. Device.GPU, block_size, num_gpu_blocks)
  204. self.cpu_allocator: BlockAllocatorBase = CachedBlockAllocator(
  205. Device.CPU, block_size, num_cpu_blocks)
  206. else:
  207. self.gpu_allocator = UncachedBlockAllocator(
  208. Device.GPU, block_size, num_gpu_blocks)
  209. self.cpu_allocator = UncachedBlockAllocator(
  210. Device.CPU, block_size, num_cpu_blocks)
  211. # Mapping: seq_id -> BlockTable.
  212. self.block_tables: Dict[int, BlockTable] = {}
  213. # Mapping: req_id -> BlockTable
  214. # Note that each SequenceGroup has a unique
  215. # request ID
  216. self.cross_block_tables: Dict[str, BlockTable] = {}
  217. def _get_seq_num_required_blocks(self, seq: Sequence) -> int:
  218. return 0 if seq is None \
  219. else len(seq.logical_token_blocks)
  220. def can_allocate(self, seq_group: SequenceGroup) -> AllocStatus:
  221. # FIXME: Here we assume that all sequences in the group share
  222. # the same prompt. This may not be true for preempted sequences.
  223. check_no_caching_or_swa_for_blockmgr_encdec(self, seq_group)
  224. self_num_required_blocks = self._get_seq_num_required_blocks(
  225. seq_group.get_seqs(status=SequenceStatus.WAITING)[0])
  226. cross_num_required_blocks = self._get_seq_num_required_blocks(
  227. seq_group.get_encoder_seq())
  228. num_required_blocks = self_num_required_blocks + \
  229. cross_num_required_blocks
  230. if self.block_sliding_window is not None:
  231. num_required_blocks = min(num_required_blocks,
  232. self.block_sliding_window)
  233. num_free_gpu_blocks = self.gpu_allocator.get_num_free_blocks()
  234. # Use watermark to avoid frequent cache eviction.
  235. if (self.num_total_gpu_blocks - num_required_blocks <
  236. self.watermark_blocks):
  237. return AllocStatus.NEVER
  238. if num_free_gpu_blocks - num_required_blocks >= self.watermark_blocks:
  239. return AllocStatus.OK
  240. else:
  241. return AllocStatus.LATER
  242. def _allocate_sequence(self, \
  243. seq: Sequence, \
  244. ref_count: int, \
  245. is_encoder_decoder: bool = True) -> BlockTable:
  246. # Allocate new physical token blocks that will store the prompt tokens.
  247. num_prompt_blocks = len(seq.logical_token_blocks)
  248. block_table: BlockTable = []
  249. for logical_idx in range(num_prompt_blocks):
  250. if (self.block_sliding_window is not None
  251. and logical_idx >= self.block_sliding_window):
  252. block = block_table[logical_idx % self.block_sliding_window]
  253. # Set the reference counts of the token blocks.
  254. block.ref_count = ref_count
  255. elif not is_encoder_decoder and self.enable_caching:
  256. block = self.gpu_allocator.allocate(
  257. seq.hash_of_block(logical_idx),
  258. seq.num_hashed_tokens_of_block(logical_idx))
  259. else:
  260. block = self.gpu_allocator.allocate()
  261. # Set the reference counts of the token blocks.
  262. block.ref_count = ref_count
  263. block_table.append(block)
  264. return block_table
  265. def allocate(self, seq_group: SequenceGroup) -> None:
  266. is_encoder_decoder = seq_group.is_encoder_decoder()
  267. check_no_caching_or_swa_for_blockmgr_encdec(self, seq_group)
  268. # Allocate decoder sequences
  269. #
  270. # NOTE: Here we assume that all sequences in the group have the same
  271. # decoder prompt.
  272. seq = seq_group.get_seqs(status=SequenceStatus.WAITING)[0]
  273. block_table: BlockTable = \
  274. self._allocate_sequence(seq,
  275. seq_group.num_seqs(),
  276. is_encoder_decoder)
  277. # Assign the self-attention block tables for each sequence.
  278. for seq in seq_group.get_seqs(status=SequenceStatus.WAITING):
  279. self.block_tables[seq.seq_id] = block_table.copy()
  280. # Allocate encoder sequence
  281. if is_encoder_decoder:
  282. # A SequenceGroup has only a single encoder sequence (at most),
  283. # thus allocate with a ref count of 1
  284. block_table = self._allocate_sequence(seq_group.get_encoder_seq(),
  285. 1, is_encoder_decoder)
  286. # Assign the cross-attention block table for the SequenceGroup.
  287. self.cross_block_tables[seq_group.request_id] = block_table
  288. def can_append_slots(self,
  289. seq_group: SequenceGroup,
  290. num_lookahead_slots: int = 0) -> bool:
  291. assert (num_lookahead_slots == 0
  292. ), "lookahead allocation not supported in BlockSpaceManagerV1"
  293. # Simple heuristic: If there is at least one free block
  294. # for each sequence, we can append.
  295. num_free_gpu_blocks = self.gpu_allocator.get_num_free_blocks()
  296. num_seqs = seq_group.num_seqs(status=SequenceStatus.RUNNING)
  297. return num_seqs <= num_free_gpu_blocks
  298. def _promote_last_block(
  299. self,
  300. seq: Sequence,
  301. last_block: PhysicalTokenBlock,
  302. ) -> PhysicalTokenBlock:
  303. assert self.enable_caching
  304. # Compute a new hash for the block so that it can be shared by other
  305. # Sequences
  306. new_hash = seq.hash_of_block(len(seq.logical_token_blocks) - 1)
  307. # if new_hash is already in the cached table, then free last_block
  308. # and return the cached version
  309. if self.gpu_allocator.contains_block(new_hash):
  310. self.gpu_allocator.free(last_block)
  311. return self.gpu_allocator.allocate(new_hash)
  312. else:
  313. self.gpu_allocator.update_hash(new_hash, last_block)
  314. return last_block
  315. def _is_last_block_full(
  316. self,
  317. seq: Sequence,
  318. ) -> bool:
  319. token_ids_len = seq.data.get_len()
  320. return token_ids_len > 0 and token_ids_len % seq.block_size == 0
  321. def _maybe_promote_last_block(
  322. self,
  323. seq: Sequence,
  324. last_block: PhysicalTokenBlock,
  325. ) -> PhysicalTokenBlock:
  326. if self._is_last_block_full(seq):
  327. return self._promote_last_block(seq, last_block)
  328. else:
  329. return last_block
  330. def _allocate_last_physical_block(
  331. self,
  332. seq: Sequence,
  333. ) -> PhysicalTokenBlock:
  334. # Called before a new block is appended.
  335. # This is in charge of allocating a new physical block (to be appended).
  336. # None if the last block is not full. Otherwise, we set it to the
  337. # content hash.
  338. if not self.enable_caching:
  339. return self.gpu_allocator.allocate()
  340. block_hash: Optional[int] = None
  341. if (self._is_last_block_full(seq)):
  342. block_hash = seq.hash_of_block(len(seq.logical_token_blocks) - 1)
  343. num_hashed_tokens = seq.num_hashed_tokens_of_block(
  344. len(seq.logical_token_blocks) - 1)
  345. # num_hashed_tokens is used to compute future hashes
  346. # (e.g. in the hashing function, it is used to ask the sequence for
  347. # prefix tokens)
  348. new_block = self.gpu_allocator.allocate(block_hash, num_hashed_tokens)
  349. # If the block has is None, then the block is not full.
  350. # If the block is not full, then we expect it to have a refcount of 1.
  351. if block_hash is None:
  352. assert new_block.ref_count == 1
  353. return new_block
  354. def append_slots(
  355. self,
  356. seq: Sequence,
  357. num_lookahead_slots: int = 0,
  358. ) -> List[Tuple[int, int]]:
  359. """Allocate a physical slot for a new token."""
  360. logical_blocks = seq.logical_token_blocks
  361. block_table = self.block_tables[seq.seq_id]
  362. # If we need to allocate a new physical block
  363. if len(block_table) < len(logical_blocks):
  364. # Currently this code only supports adding one physical block
  365. assert len(block_table) == len(logical_blocks) - 1
  366. if (self.block_sliding_window
  367. and len(block_table) >= self.block_sliding_window):
  368. # reuse a block
  369. block_table.append(block_table[len(block_table) %
  370. self.block_sliding_window])
  371. else:
  372. # The sequence hash a new logical block.
  373. # Allocate a new physical block.
  374. new_block = self._allocate_last_physical_block(seq)
  375. block_table.append(new_block)
  376. return []
  377. # We want to append the token to the last physical block.
  378. last_block = block_table[-1]
  379. assert last_block.device == Device.GPU
  380. if last_block.ref_count == 1:
  381. # Not shared with other sequences. Appendable.
  382. if self.enable_caching:
  383. # If the last block is now complete, we may reuse an old block
  384. # to save memory.
  385. maybe_new_block = self._maybe_promote_last_block(
  386. seq, last_block)
  387. block_table[-1] = maybe_new_block
  388. return []
  389. else:
  390. # The last block is shared with other sequences.
  391. # Copy on Write: Allocate a new block and copy the tokens.
  392. new_block = self._allocate_last_physical_block(seq)
  393. block_table[-1] = new_block
  394. self.gpu_allocator.free(last_block)
  395. return [(last_block.block_number, new_block.block_number)]
  396. def fork(self, parent_seq: Sequence, child_seq: Sequence) -> None:
  397. # NOTE: fork does not allocate a new physical block.
  398. # Thus, it is always safe from OOM.
  399. src_block_table = self.block_tables[parent_seq.seq_id]
  400. self.block_tables[child_seq.seq_id] = src_block_table.copy()
  401. # When using a sliding window, blocks will be eventually reused.
  402. # In this case the block tables will contain repeated blocks.
  403. # When forking, we must make sure that each block's `ref_count`
  404. # is only incremented by one, so we deduplicate them by wrapping
  405. # them in a set.
  406. for block in set(src_block_table):
  407. block.ref_count += 1
  408. def _get_physical_blocks(
  409. self, seq_group: SequenceGroup) -> List[PhysicalTokenBlock]:
  410. # NOTE: Here, we assume that the physical blocks are only shared by
  411. # the sequences in the same group.
  412. request_id = seq_group.request_id
  413. blocks: Set[PhysicalTokenBlock] = set()
  414. for seq in seq_group.get_seqs():
  415. if seq.is_finished():
  416. continue
  417. blocks.update(self.block_tables[seq.seq_id])
  418. # Cross-attention blocks
  419. if seq_group.is_encoder_decoder():
  420. blocks.update(self.cross_block_tables[request_id])
  421. return list(blocks)
  422. def can_swap_in(self,
  423. seq_group: SequenceGroup,
  424. num_lookahead_slots: int = 0) -> AllocStatus:
  425. assert (num_lookahead_slots == 0
  426. ), "BlockSpaceManagerV1 does not support lookahead allocation"
  427. blocks = self._get_physical_blocks(seq_group)
  428. num_swapped_seqs = seq_group.num_seqs(status=SequenceStatus.SWAPPED)
  429. if seq_group.is_encoder_decoder():
  430. num_swapped_seqs += 1
  431. num_free_blocks = self.gpu_allocator.get_num_free_blocks()
  432. # NOTE: Conservatively, we assume that every sequence will allocate
  433. # at least one free block right after the swap-in.
  434. # NOTE: This should match the logic in can_append_slot().
  435. num_required_blocks = len(blocks) + num_swapped_seqs
  436. if self.gpu_allocator.get_num_total_blocks() < num_required_blocks:
  437. return AllocStatus.NEVER
  438. elif num_free_blocks - num_required_blocks >= self.watermark_blocks:
  439. return AllocStatus.OK
  440. else:
  441. return AllocStatus.LATER
  442. def _swap_block_table(
  443. self, block_table: BlockTable, src_allocator: BlockAllocatorBase,
  444. dest_allocator: BlockAllocatorBase,
  445. mapping: Dict[PhysicalTokenBlock,
  446. PhysicalTokenBlock]) -> BlockTable:
  447. new_block_table = []
  448. for from_block in block_table:
  449. if from_block in mapping:
  450. to_block = mapping[from_block]
  451. to_block.ref_count += 1
  452. else:
  453. to_block = dest_allocator.allocate(
  454. from_block.block_hash, from_block.num_hashed_tokens)
  455. mapping[from_block] = to_block
  456. new_block_table.append(to_block)
  457. # Free the source block swapped in to destination.
  458. src_allocator.free(from_block)
  459. return new_block_table
  460. def swap_in(self, seq_group: SequenceGroup) -> List[Tuple[int, int]]:
  461. request_id = seq_group.request_id
  462. # CPU block -> GPU block.
  463. # dict is efficient in lookup `if cpu_block in mapping`
  464. mapping: Dict[PhysicalTokenBlock, PhysicalTokenBlock] = {}
  465. for seq in seq_group.get_seqs(status=SequenceStatus.SWAPPED):
  466. self.block_tables[seq.seq_id] = \
  467. self._swap_block_table(self.block_tables[seq.seq_id],
  468. self.cpu_allocator,
  469. self.gpu_allocator,
  470. mapping)
  471. if seq_group.is_encoder_decoder():
  472. self.cross_block_tables[request_id] = \
  473. self._swap_block_table(self.cross_block_tables[request_id],
  474. self.cpu_allocator,
  475. self.gpu_allocator,
  476. mapping)
  477. return [(cpu_block.block_number, gpu_block.block_number)
  478. for cpu_block, gpu_block in mapping.items()]
  479. def can_swap_out(self, seq_group: SequenceGroup) -> bool:
  480. blocks = self._get_physical_blocks(seq_group)
  481. return len(blocks) <= self.cpu_allocator.get_num_free_blocks()
  482. def swap_out(self, seq_group: SequenceGroup) -> List[Tuple[int, int]]:
  483. request_id = seq_group.request_id
  484. # GPU block -> CPU block.
  485. # dict is efficient in lookup `if gpu_block in mapping`
  486. mapping: Dict[PhysicalTokenBlock, PhysicalTokenBlock] = {}
  487. for seq in seq_group.get_seqs(status=SequenceStatus.RUNNING):
  488. self.block_tables[seq.seq_id] = \
  489. self._swap_block_table(self.block_tables[seq.seq_id],
  490. self.gpu_allocator,
  491. self.cpu_allocator,
  492. mapping)
  493. if seq_group.is_encoder_decoder():
  494. self.cross_block_tables[request_id] = \
  495. self._swap_block_table(self.cross_block_tables[request_id],
  496. self.gpu_allocator,
  497. self.cpu_allocator,
  498. mapping)
  499. return [(cpu_block.block_number, gpu_block.block_number)
  500. for cpu_block, gpu_block in mapping.items()]
  501. def _free_block_table(self, block_table: BlockTable) -> None:
  502. # when using a sliding window, each seq will only use up
  503. # to `self.block_sliding_window` blocks. When freeing
  504. # the block table, we must make sure to not free blocks more
  505. # than once. If no sliding window is used, there is no block
  506. # reuse in the block table, so we must free all blocks.
  507. blocks_to_free = (block_table[-self.block_sliding_window:]
  508. if self.block_sliding_window is not None else
  509. block_table)
  510. for block in set(blocks_to_free):
  511. if block.device == Device.GPU:
  512. self.gpu_allocator.free(block)
  513. else:
  514. self.cpu_allocator.free(block)
  515. def free(self, seq: Sequence) -> None:
  516. if seq.seq_id not in self.block_tables:
  517. # Already freed or haven't been scheduled yet.
  518. return
  519. block_table = self.block_tables[seq.seq_id]
  520. self._free_block_table(block_table)
  521. del self.block_tables[seq.seq_id]
  522. def free_cross(self, seq_group: SequenceGroup) -> None:
  523. if seq_group.request_id not in self.cross_block_tables:
  524. # Already freed or hasn't ben scheduled yet.
  525. return
  526. block_table = self.cross_block_tables[seq_group.request_id]
  527. self._free_block_table(block_table)
  528. del self.cross_block_tables[seq_group.request_id]
  529. def reset(self) -> None:
  530. # Free decoder block tables
  531. for block_table in self.block_tables.values():
  532. self._free_block_table(block_table)
  533. self.block_tables.clear()
  534. # Free cross-attention block tables
  535. for block_table in self.cross_block_tables.values():
  536. self._free_block_table(block_table)
  537. self.cross_block_tables.clear()
  538. def get_block_table(self, seq: Sequence) -> List[int]:
  539. block_table = self.block_tables[seq.seq_id]
  540. return [block.block_number for block in block_table]
  541. def get_cross_block_table(self, seq_group: SequenceGroup) -> List[int]:
  542. block_table = self.cross_block_tables[seq_group.request_id]
  543. return [block.block_number for block in block_table]
  544. def get_num_free_gpu_blocks(self) -> int:
  545. return self.gpu_allocator.get_num_free_blocks()
  546. def get_num_free_cpu_blocks(self) -> int:
  547. return self.cpu_allocator.get_num_free_blocks()
  548. def access_all_blocks_in_seq(
  549. self,
  550. seq: Sequence,
  551. access_time: float,
  552. ) -> None:
  553. if self.enable_caching:
  554. # Update the last accessed time of all the blocks accessed
  555. # in this step.
  556. block_table = self.block_tables[seq.seq_id]
  557. for block in block_table:
  558. block.last_accessed = access_time
  559. def compute_full_blocks_in_seq(self, seq: Sequence):
  560. if seq.seq_id not in self.block_tables:
  561. return
  562. max_full_block = seq.get_len() // self.block_size - 1
  563. block_table = self.block_tables[seq.seq_id]
  564. if max_full_block == -1:
  565. return
  566. for i in reversed(range(max_full_block)):
  567. if block_table[i].computed:
  568. break
  569. block_table[i].computed = True
  570. def get_all_computed_blocks(self, seq: Sequence) -> List[int]:
  571. if seq.seq_id not in self.block_tables:
  572. return []
  573. block_table = self.block_tables[seq.seq_id]
  574. # NOTE We exclude the last block to avoid the case where the entire
  575. # prompt is cached. This would cause erroneous behavior in model
  576. # runner.
  577. return [
  578. b.block_number
  579. for b in takewhile(lambda b: b.computed, block_table[:-1])
  580. ]
  581. def get_common_computed_block_ids(
  582. self, seqs: List[Sequence]) -> GenericSequence[int]:
  583. """Return the block ids that are common for a given sequence group.
  584. Used in prefill (can skip prefill of some blocks).
  585. """
  586. # Can return non-empty result only with prefix caching enabled.
  587. if not self.enable_caching:
  588. return []
  589. ids_list = [self.get_all_computed_blocks(seq) for seq in seqs]
  590. return commonprefix([ids for ids in ids_list if ids != []])
  591. def mark_blocks_as_computed(self, seq_group: SequenceGroup):
  592. if self.enable_caching:
  593. for seq in seq_group.seqs_dict.values():
  594. self.compute_full_blocks_in_seq(seq)