naive_block.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. from typing import Dict, Iterable, List, Optional, Set
  2. from aphrodite.processing.block.common import (CopyOnWriteTracker, RefCounter,
  3. get_all_blocks_recursively)
  4. from aphrodite.processing.block.interfaces import Block, BlockAllocator
  5. BlockId = int
  6. Refcount = int
  7. class NaiveBlockAllocator(BlockAllocator):
  8. """A simple block allocator that manages blocks of memory without prefix
  9. caching.
  10. Args:
  11. create_block (Block.Factory): A factory function for creating new
  12. blocks. This is used when a NaiveBlockAllocator is composed within
  13. a prefix caching allocator -- the naive block allocator must
  14. construct prefix caching blocks (but shouldn't know anything else
  15. about them).
  16. num_blocks (int): The total number of blocks to manage.
  17. block_size (int): The size of each block in tokens.
  18. block_ids (Optional[Iterable[int]], optional): An optional iterable of
  19. block IDs. If not provided, block IDs will be assigned sequentially
  20. from 0 to num_blocks - 1.
  21. """
  22. def __init__(
  23. self,
  24. create_block: Block.Factory,
  25. num_blocks: int,
  26. block_size: int,
  27. block_ids: Optional[Iterable[int]] = None,
  28. ):
  29. if block_ids is None:
  30. block_ids = range(num_blocks)
  31. self._free_block_indices: Set[BlockId] = set(block_ids)
  32. self._all_block_indices = frozenset(block_ids)
  33. assert len(self._all_block_indices) == num_blocks
  34. self._refcounter = RefCounter(
  35. all_block_indices=self._free_block_indices)
  36. self._create_block = create_block
  37. self._block_size = block_size
  38. self._cow_tracker = CopyOnWriteTracker(
  39. refcounter=self._refcounter.as_readonly(),
  40. allocator=self,
  41. )
  42. def allocate_immutable(self, prev_block: Optional[Block],
  43. token_ids: List[int]) -> Block:
  44. """Allocates a new immutable block with the given token IDs, linked to
  45. the previous block.
  46. Args:
  47. prev_block (Optional[Block]): The previous block in the sequence. If
  48. None, then the block to be allocated is the first block in the
  49. sequence.
  50. token_ids (List[int]): The token IDs to be stored in the new block.
  51. Returns:
  52. Block: The newly allocated immutable block.
  53. """
  54. block = self.allocate_mutable(prev_block=prev_block)
  55. block.append_token_ids(token_ids)
  56. return block
  57. def allocate_mutable(self, prev_block: Optional[Block]) -> Block:
  58. """Allocates a new mutable block, linked to the previous block.
  59. Args:
  60. prev_block (Optional[Block]): The previous block in the sequence. If
  61. None, then the block to be allocated is the first block in the
  62. sequence.
  63. Returns:
  64. Block: The newly allocated mutable block.
  65. """
  66. block_id = self._allocate_new_block_id()
  67. return self._create_block(
  68. prev_block=prev_block,
  69. token_ids=[],
  70. block_id=block_id,
  71. block_size=self._block_size,
  72. allocator=self,
  73. )
  74. def free(self, block: Block) -> None:
  75. self._free_block_id(block.block_id)
  76. # Mark the block as having no allocation.
  77. block.block_id = None
  78. def fork(self, last_block: Block) -> List[Block]:
  79. """Creates a new sequence of blocks that shares the same underlying
  80. memory as the original sequence.
  81. Args:
  82. last_block (Block): The last block in the original sequence.
  83. Returns:
  84. List[Block]: The new sequence of blocks that shares the same memory
  85. as the original sequence.
  86. """
  87. source_blocks = get_all_blocks_recursively(last_block)
  88. forked_blocks = []
  89. prev_block = None
  90. for block in source_blocks:
  91. # Increment refcount for each block.
  92. refcount = self._refcounter.incr(block.block_id)
  93. assert refcount != 1, "can't fork free'd block"
  94. forked_blocks.append(
  95. self._create_block(
  96. prev_block=prev_block,
  97. token_ids=block.token_ids,
  98. block_id=block.block_id,
  99. block_size=self._block_size,
  100. allocator=self,
  101. ))
  102. prev_block = forked_blocks[-1]
  103. return forked_blocks
  104. def get_num_free_blocks(self) -> int:
  105. return len(self._free_block_indices)
  106. def _allocate_new_block_id(self) -> BlockId:
  107. if not self._free_block_indices:
  108. raise BlockAllocator.NoFreeBlocksError()
  109. block_id = next(iter(self._free_block_indices))
  110. self._refcounter.incr(block_id)
  111. self._free_block_indices.remove(block_id)
  112. return block_id
  113. def _free_block_id(self, block_id: BlockId) -> None:
  114. refcount = self._refcounter.decr(block_id)
  115. if refcount == 0:
  116. self._free_block_indices.add(block_id)
  117. @property
  118. def refcounter(self):
  119. return self._refcounter
  120. @property
  121. def all_block_ids(self):
  122. return self._all_block_indices
  123. def cow_block_if_not_appendable(self, block: Block) -> Optional[BlockId]:
  124. """Performs a copy-on-write operation on the given block if it is not
  125. appendable.
  126. Args:
  127. block (Block): The block to check for copy-on-write.
  128. Returns:
  129. Optional[BlockId]: The block index of the new block if a copy-on
  130. -write operation was performed, or the original block index if
  131. no copy-on-write was necessary.
  132. """
  133. return self._cow_tracker.cow_block_if_not_appendable(block)
  134. def clear_copy_on_writes(self) -> Dict[BlockId, List[BlockId]]:
  135. """Returns the copy-on-write source->destination mapping and clears it.
  136. Returns:
  137. Dict[BlockId, List[BlockId]]: A dictionary mapping source
  138. block indices to lists of destination block indices.
  139. """
  140. return self._cow_tracker.clear_cows()
  141. def mark_blocks_as_computed(self) -> None:
  142. """Mark blocks as computed, used in prefix caching.
  143. Since the naive allocator does not implement prefix caching, we do
  144. nothing.
  145. """
  146. pass
  147. def get_common_computed_block_ids(
  148. self, seq_block_ids: List[List[int]]) -> List[int]:
  149. """Determine blocks that can be skipped in prefill.
  150. Since the naive allocator does not support prefix caching, always return
  151. an empty list.
  152. """
  153. return []
  154. class NaiveBlock(Block):
  155. """An implementation of the Block class that does not support prefix
  156. caching.
  157. The NaiveBlock class represents a block of token IDs with a fixed size. It
  158. provides methods for appending token IDs to the block and manages copy-on
  159. -write operations when necessary.
  160. Args:
  161. prev_block (Block): The previous block in the sequence.
  162. token_ids (List[int]): The initial token IDs to be stored in the block.
  163. block_size (int): The maximum number of token IDs that can be stored in
  164. the block.
  165. allocator (BlockAllocator): The block allocator associated with this
  166. block.
  167. block_id (Optional[int], optional): The physical block index
  168. of this block. Defaults to None, which means no allocation has been
  169. made.
  170. _cow_target (Optional[Block], optional): The copy-on-write target block.
  171. If not provided, it defaults to self.
  172. """
  173. def __init__(self,
  174. prev_block: Block,
  175. token_ids: List[int],
  176. block_size: int,
  177. allocator: BlockAllocator,
  178. block_id: Optional[int] = None,
  179. _cow_target: Optional[Block] = None):
  180. self._token_ids = []
  181. self._block_size = block_size
  182. self._prev_block = prev_block
  183. self._block_id = block_id
  184. self._allocator = allocator
  185. self._cow_target = _cow_target if _cow_target is not None else self
  186. self._append_token_ids_no_cow(token_ids)
  187. def append_token_ids(self, token_ids: List[int]) -> None:
  188. """Appends the given token IDs to the block, instructing the allocator
  189. to perform a copy-on-write if necessary.
  190. Args:
  191. token_ids (List[int]): The token IDs to be appended to the block.
  192. """
  193. self._append_token_ids_no_cow(token_ids)
  194. if self._block_id is not None:
  195. self._block_id = (self._allocator.cow_block_if_not_appendable(
  196. self._cow_target))
  197. def _append_token_ids_no_cow(self, token_ids: List[int]) -> None:
  198. assert self.num_empty_slots >= len(token_ids)
  199. self._token_ids.extend(token_ids)
  200. @property
  201. def block_id(self) -> Optional[int]:
  202. return self._block_id
  203. @block_id.setter
  204. def block_id(self, value: Optional[int]) -> None:
  205. self._block_id = value
  206. @property
  207. def is_full(self) -> bool:
  208. return self.num_empty_slots == 0
  209. @property
  210. def num_empty_slots(self) -> int:
  211. return self._block_size - len(self._token_ids)
  212. @property
  213. def token_ids(self) -> List[int]:
  214. return self._token_ids
  215. def block_size(self) -> int:
  216. return self._block_size
  217. @property
  218. def prev_block(self) -> Optional["Block"]:
  219. return self._prev_block