1
0

common.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. from collections import deque
  2. from typing import Deque, Dict, Iterable, List, Optional, Protocol, Tuple
  3. from aphrodite.processing.block.interfaces import Block, BlockAllocator
  4. BlockId = int
  5. RefCount = int
  6. class RefCounterProtocol(Protocol):
  7. def incr(self, block_id: BlockId) -> RefCount:
  8. raise NotImplementedError
  9. def decr(self, block_id: BlockId) -> RefCount:
  10. raise NotImplementedError
  11. def get(self, block_id: BlockId) -> RefCount:
  12. raise NotImplementedError
  13. class RefCounter(RefCounterProtocol):
  14. """A class for managing reference counts for a set of block indices.
  15. The RefCounter class maintains a dictionary that maps block indices to their
  16. corresponding reference counts. It provides methods to increment, decrement,
  17. and retrieve the reference count for a given block index.
  18. Args:
  19. all_block_indices (Iterable[BlockId]): An iterable of block indices
  20. to initialize the reference counter with.
  21. """
  22. def __init__(self, all_block_indices: Iterable[BlockId]):
  23. deduped = set(all_block_indices)
  24. self._refcounts: Dict[BlockId,
  25. RefCount] = {index: 0
  26. for index in deduped}
  27. def incr(self, block_id: BlockId) -> RefCount:
  28. assert block_id in self._refcounts
  29. pre_incr_refcount = self._refcounts[block_id]
  30. assert pre_incr_refcount >= 0
  31. post_incr_refcount = pre_incr_refcount + 1
  32. self._refcounts[block_id] = post_incr_refcount
  33. return post_incr_refcount
  34. def decr(self, block_id: BlockId) -> RefCount:
  35. assert block_id in self._refcounts
  36. refcount = self._refcounts[block_id]
  37. assert refcount > 0
  38. refcount -= 1
  39. self._refcounts[block_id] = refcount
  40. return refcount
  41. def get(self, block_id: BlockId) -> RefCount:
  42. assert block_id in self._refcounts
  43. return self._refcounts[block_id]
  44. def as_readonly(self) -> "ReadOnlyRefCounter":
  45. return ReadOnlyRefCounter(self)
  46. class ReadOnlyRefCounter(RefCounterProtocol):
  47. """A read-only view of the RefCounter class.
  48. The ReadOnlyRefCounter class provides a read-only interface to access the
  49. reference counts maintained by a RefCounter instance. It does not allow
  50. modifications to the reference counts.
  51. Args:
  52. refcounter (RefCounter): The RefCounter instance to create a read-only
  53. view for.
  54. """
  55. def __init__(self, refcounter: RefCounter):
  56. self._refcounter = refcounter
  57. def incr(self, block_id: BlockId) -> RefCount:
  58. raise ValueError("Incr not allowed")
  59. def decr(self, block_id: BlockId) -> RefCount:
  60. raise ValueError("Decr not allowed")
  61. def get(self, block_id: BlockId) -> RefCount:
  62. return self._refcounter.get(block_id)
  63. class CopyOnWriteTracker:
  64. """A class for tracking and managing copy-on-write operations for blocks.
  65. The CopyOnWriteTracker class maintains a mapping of source block indices to
  66. their corresponding copy-on-write destination block indices. It works in
  67. conjunction with a RefCounter.
  68. Args:
  69. refcounter (RefCounter): The reference counter used to track block
  70. reference counts.
  71. """
  72. def __init__(self, refcounter: RefCounterProtocol):
  73. self._copy_on_writes: List[Tuple[BlockId, BlockId]] = []
  74. self._refcounter = refcounter
  75. def is_appendable(self, block: Block) -> bool:
  76. """Checks if the block is shared or not. If shared, then it cannot
  77. be appended and needs to be duplicated via copy-on-write
  78. """
  79. block_id = block.block_id
  80. if block_id is None:
  81. return True
  82. refcount = self._refcounter.get(block_id)
  83. return refcount <= 1
  84. def record_cow(self, src_block_id: Optional[BlockId],
  85. trg_block_id: Optional[BlockId]) -> None:
  86. """Records a copy-on-write operation from source to target block id
  87. Args:
  88. src_block_id (BlockId): The source block id from which to copy
  89. the data
  90. trg_block_id (BlockId): The target block id to which the data
  91. is copied
  92. """
  93. assert src_block_id is not None
  94. assert trg_block_id is not None
  95. self._copy_on_writes.append((src_block_id, trg_block_id))
  96. def clear_cows(self) -> List[Tuple[BlockId, BlockId]]:
  97. """Clears the copy-on-write tracking information and returns the current
  98. state.
  99. This method returns a list mapping source block indices to
  100. destination block indices for the current copy-on-write operations.
  101. It then clears the internal tracking information.
  102. Returns:
  103. List[Tuple[BlockId, BlockId]]: A list mapping source
  104. block indices to destination block indices for the
  105. current copy-on-write operations.
  106. """
  107. cows = self._copy_on_writes
  108. self._copy_on_writes = []
  109. return cows
  110. class BlockPool:
  111. """Used to pre-allocate block objects, in order to avoid excessive python
  112. object allocations/deallocations.
  113. The pool starts from "pool_size" objects and will increase to more objects
  114. if necessary
  115. Note that multiple block objects may point to the same physical block id,
  116. which is why this pool is needed, so that it will be easier to support
  117. prefix caching and more complicated sharing of physical blocks.
  118. """
  119. def __init__(self, block_size: int, create_block: Block.Factory,
  120. allocator: BlockAllocator, pool_size: int):
  121. self._block_size = block_size
  122. self._create_block = create_block
  123. self._allocator = allocator
  124. self._pool_size = pool_size
  125. assert self._pool_size >= 0
  126. self._free_ids: Deque[int] = deque(range(self._pool_size))
  127. self._pool = []
  128. for i in range(self._pool_size):
  129. self._pool.append(
  130. self._create_block(prev_block=None,
  131. token_ids=[],
  132. block_size=self._block_size,
  133. allocator=self._allocator,
  134. block_id=None))
  135. def increase_pool(self):
  136. """Doubles the internal pool size
  137. """
  138. cur_pool_size = self._pool_size
  139. new_pool_size = cur_pool_size * 2
  140. self._pool_size = new_pool_size
  141. self._free_ids += deque(range(cur_pool_size, new_pool_size))
  142. for i in range(cur_pool_size, new_pool_size):
  143. self._pool.append(
  144. self._create_block(prev_block=None,
  145. token_ids=[],
  146. block_size=self._block_size,
  147. allocator=self._allocator,
  148. block_id=None))
  149. def init_block(self, prev_block: Optional[Block], token_ids: List[int],
  150. block_size: int, physical_block_id: Optional[int]) -> Block:
  151. if len(self._free_ids) == 0:
  152. self.increase_pool()
  153. assert len(self._free_ids) > 0
  154. pool_id = self._free_ids.popleft()
  155. block = self._pool[pool_id]
  156. block.__init__( # type: ignore[misc]
  157. prev_block=prev_block,
  158. token_ids=token_ids,
  159. block_size=block_size,
  160. allocator=block._allocator, # type: ignore[attr-defined]
  161. block_id=physical_block_id)
  162. block.pool_id = pool_id # type: ignore[attr-defined]
  163. return block
  164. def free_block(self, block: Block) -> None:
  165. self._free_ids.appendleft(block.pool_id) # type: ignore[attr-defined]
  166. class BlockList:
  167. """This class is an optimization to allow fast-access to physical
  168. block ids. It maintains a block id list that is updated with the
  169. block list and this avoids the need to reconstruct the block id
  170. list on every iteration of the block manager
  171. """
  172. def __init__(self, blocks: List[Block]):
  173. self._blocks: List[Block] = []
  174. self._block_ids: List[int] = []
  175. self.update(blocks)
  176. def _add_block_id(self, block_id: Optional[BlockId]) -> None:
  177. assert block_id is not None
  178. self._block_ids.append(block_id)
  179. def _update_block_id(self, block_index: int,
  180. new_block_id: Optional[BlockId]) -> None:
  181. assert new_block_id is not None
  182. self._block_ids[block_index] = new_block_id
  183. def update(self, blocks: List[Block]):
  184. self._blocks = blocks
  185. # Cache block ids for fast query
  186. self._block_ids = []
  187. for block in self._blocks:
  188. self._add_block_id(block.block_id)
  189. def append_token_ids(self, block_index: int, token_ids: List[int]) -> None:
  190. block = self._blocks[block_index]
  191. prev_block_id = block.block_id
  192. block.append_token_ids(token_ids)
  193. # CoW or promotion may update the internal block_id
  194. if prev_block_id != block.block_id:
  195. self._update_block_id(block_index, block.block_id)
  196. def append(self, new_block: Block):
  197. self._blocks.append(new_block)
  198. self._add_block_id(new_block.block_id)
  199. def __len__(self) -> int:
  200. return len(self._blocks)
  201. def __getitem__(self, block_index: int) -> Block:
  202. return self._blocks[block_index]
  203. def __setitem__(self, block_index: int, new_block: Block) -> None:
  204. self._blocks[block_index] = new_block
  205. self._update_block_id(block_index, new_block.block_id)
  206. def reset(self):
  207. self._blocks = []
  208. self._block_ids = []
  209. def list(self) -> List[Block]:
  210. return self._blocks
  211. def ids(self) -> List[int]:
  212. return self._block_ids
  213. def get_all_blocks_recursively(last_block: Block) -> List[Block]:
  214. """Retrieves all the blocks in a sequence starting from the last block.
  215. This function recursively traverses the sequence of blocks in reverse order,
  216. starting from the given last block, and returns a list of all the blocks in
  217. the sequence.
  218. Args:
  219. last_block (Block): The last block in the sequence.
  220. Returns:
  221. List[Block]: A list of all the blocks in the sequence, in the order they
  222. appear.
  223. """
  224. def recurse(block: Block, lst: List[Block]) -> None:
  225. if block.prev_block is not None:
  226. recurse(block.prev_block, lst)
  227. lst.append(block)
  228. all_blocks: List[Block] = []
  229. recurse(last_block, all_blocks)
  230. return all_blocks