cache.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. """
  2. A pytorch memory cache that can be allocated by ConnectionHandler (on cpu) and used over multiple calls to Runtime.
  3. For now, the only purpose of this code is to ensure that allocated memory will be deleted properly.
  4. """
  5. import contextlib
  6. import ctypes
  7. import multiprocessing as mp
  8. import os
  9. from typing import AsyncContextManager, Dict, Optional, Union
  10. import hivemind
  11. import torch
  12. from hivemind import use_hivemind_log_handler
  13. from hivemind.utils import TensorDescriptor, get_logger
  14. use_hivemind_log_handler("in_root_logger")
  15. logger = get_logger(__file__)
  16. Handle = int
  17. class MemoryCache:
  18. """A shared cache for storing tensors that persist across calls. Main use case: storing past attention KVs"""
  19. def __init__(self, device: Union[str, torch.device], max_size_bytes: Optional[int]):
  20. self.max_size_bytes = max_size_bytes if max_size_bytes is not None else (2**64 - 1)
  21. self.device = device
  22. self.lock_metadata, self.size_decreased_event = mp.Lock(), mp.Event()
  23. self._current_size = mp.Value(ctypes.c_int64, 0, lock=False)
  24. self._handle_counter = mp.Value(ctypes.c_int64, 0, lock=False)
  25. self._active_handles: Optional[Dict[Handle, TensorDescriptor]] = None
  26. self._allocated_tensors: Optional[Dict[Handle, torch.Tensor]] = None
  27. self.runtime_pid = os.getpid()
  28. self._pipe_recv, self._pipe_send = mp.Pipe(duplex=False) # any ConnectionHandler -> runtime
  29. self._pending_messages = mp.Value(ctypes.c_int64, 0, lock=False)
  30. @property
  31. def current_size_bytes(self) -> int:
  32. return self._current_size.value
  33. @current_size_bytes.setter
  34. def current_size_bytes(self, value: int):
  35. self._current_size.value = value
  36. @property
  37. def handle_counter(self) -> int:
  38. return self._handle_counter.value
  39. @handle_counter.setter
  40. def handle_counter(self, value: int):
  41. self._handle_counter.value = value
  42. @contextlib.asynccontextmanager
  43. async def allocate_cache(self, descr: TensorDescriptor) -> AsyncContextManager[Handle]:
  44. """
  45. Create a handle that is associated with buffers on unique device. If cache full, raises AllocationFailed.
  46. :param descr: allocate a tensor of this size, dtype, etc
  47. :note: This function should be called by connection handlers, it can be called concurrently from multiple processes.
  48. Furthermore, it can be called concurrently with at most one use_cache call in runtime.
  49. """
  50. assert os.getpid() != self.runtime_pid, "must be called by a ConnectionHandler, not runtime"
  51. assert descr.device is None and descr
  52. allocated_handle = None
  53. allocated_size_bytes = descr.numel() * torch.finfo(descr.dtype).bits // 8
  54. try:
  55. async with hivemind.utils.enter_asynchronously(self.lock_metadata):
  56. if self.current_size_bytes + allocated_size_bytes > self.max_size_bytes:
  57. raise AllocationFailed(
  58. f"Could not allocate {allocated_size_bytes} bytes in cache; cache size = "
  59. f"{self.max_size_bytes} bytes; {self.current_size_bytes} already allocated."
  60. )
  61. allocated_handle = int(self.handle_counter)
  62. self.current_size_bytes += allocated_size_bytes
  63. self.handle_counter += 1 # note: this will eventually overflow and it is okay
  64. self._pending_messages.value += 1
  65. self._pipe_send.send((allocated_handle, descr))
  66. yield allocated_handle
  67. finally:
  68. if allocated_handle is not None:
  69. async with hivemind.utils.enter_asynchronously(self.lock_metadata):
  70. self._pending_messages.value += 1
  71. self._pipe_send.send((allocated_handle, None)) # signal runtime to free that handle
  72. self.current_size_bytes -= allocated_size_bytes
  73. @contextlib.contextmanager
  74. def use_cache(self, handle: Handle) -> torch.Tensor:
  75. """
  76. Return a tensor that was previously allocated with try_allocate_cache,
  77. :note: This method is called by ExpertBackend in runtime: a single process with NO process parallelism.
  78. However, runtime may call use_cache concurrently with one or more connection handlers calling allocate_cache
  79. """
  80. assert os.getpid() == self.runtime_pid
  81. # note: this specific function is not concurrent, so you can safely allocate/offload/defragment data here
  82. with self.lock_metadata:
  83. if self._allocated_tensors is None:
  84. self._allocated_tensors = {}
  85. # read creation/deletion requests from connection handlers
  86. for i in range(int(self._pending_messages.value)):
  87. recv_handle, recv_data = self._pipe_recv.recv()
  88. self._pending_messages.value -= 1
  89. if isinstance(recv_data, TensorDescriptor):
  90. self._allocated_tensors[recv_handle] = recv_data.make_zeros(device=self.device)
  91. elif recv_data is None:
  92. if recv_handle not in self._allocated_tensors:
  93. logger.warning(
  94. f"Sanity check failed: asked to delete handle {recv_handle}, but there is no such handle"
  95. )
  96. self._allocated_tensors.pop(recv_handle, None)
  97. else:
  98. logger.error(f"MemoryCache pipe received unexpected message: {recv_data}")
  99. assert handle in self._allocated_tensors, f"Sanity check failed: no such handle ({handle})"
  100. yield self._allocated_tensors[handle]
  101. class AllocationFailed(Exception):
  102. pass