remote_block.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. # Note: this code is being actively modified by justheuristic. If you want to change anything about it, please warn me.
  2. from __future__ import annotations
  3. import asyncio
  4. import random
  5. from typing import Any, AsyncIterator, Dict, Optional
  6. import torch
  7. from hivemind.compression import deserialize_torch_tensor, serialize_torch_tensor
  8. from hivemind.moe.client.expert import RemoteExpert, RemoteExpertWorker
  9. from hivemind.moe.expert_uid import ExpertInfo
  10. from hivemind.p2p import P2P, StubBase
  11. from hivemind.proto import runtime_pb2
  12. from hivemind.utils import anext, nested_flatten, use_hivemind_log_handler, get_logger
  13. from src.data_structures import RemoteModuleInfo
  14. from src.dht_utils import ModuleUID
  15. from src.server.handler import TransformerConnectionHandler
  16. use_hivemind_log_handler("in_root_logger")
  17. logger = get_logger(__file__)
  18. class RemoteTransformerBlock(RemoteExpert):
  19. """A class that interacts with a remote module on a specific server for forward/backward or inference"""
  20. def __init__(self, peers_info: RemoteModuleInfo, p2p: P2P):
  21. peer_info = ExpertInfo(peers_info.uid, random.choice(list(peers_info.peer_ids))) # TODO replace this
  22. super().__init__(peer_info, p2p)
  23. @property
  24. def stub(self) -> StubBase:
  25. return TransformerConnectionHandler.get_stub(self.p2p, self.peer_id)
  26. def forward(self, inputs: torch.Tensor, **kwargs):
  27. for k, v in kwargs.items():
  28. assert v is None, f"Extra keyword arguments are not yet supported (got {k} = {v})"
  29. return super().forward(inputs)
  30. def inference_session(self) -> RemoteTransformerBlockInferenceSession:
  31. """Initialize a new inference session with the specified remote server"""
  32. _ = self.info # create _info manually since the built-in property will not work inside RemoteExpertWorker
  33. return RemoteExpertWorker.run_coroutine(RemoteTransformerBlockInferenceSession._create(self))
  34. def begin_inference_session(self):
  35. logger.warning("beging_inference_session was renamed to just inference_session")
  36. return self.inference_session()
  37. class RemoteTransformerBlockInferenceSession:
  38. """An interface to a single multi-step *inference* session for a specific remote module with a specific server"""
  39. def __init__(self, uid: ModuleUID, info: Dict[str, Any], inputs_queue: asyncio.Queue, outputs_aiter: AsyncIterator):
  40. self.uid, self.info = uid, info
  41. # warning: this code manages async objects that are only usable inside RemoteExpertWorker's background thread;
  42. # using them in any other EventLoop may cause side-effects including, headaches, diarrhea, and loss of sleep
  43. self._inputs_queue: asyncio.Queue[runtime_pb2.ExpertRequest] = inputs_queue
  44. self._outputs_stream: AsyncIterator[runtime_pb2.ExpertResponse] = outputs_aiter
  45. self.stepped = False
  46. self.closed = False
  47. @classmethod
  48. async def _create(
  49. cls, remote_module: RemoteTransformerBlock, timeout: Optional[float] = None
  50. ) -> RemoteTransformerBlockInferenceSession:
  51. """Create a new session for a given remote module. This code is meant to be run inside RemoteExpertWorker"""
  52. inputs_queue = asyncio.Queue()
  53. outputs_stream = await remote_module.stub.rpc_inference(
  54. cls._read_inputs_from_queue(inputs_queue, timeout), timeout=timeout
  55. )
  56. return cls(remote_module.uid, remote_module.info, inputs_queue, outputs_stream)
  57. @staticmethod
  58. async def _read_inputs_from_queue(queue: asyncio.Queue, timeout: Optional[float]) -> AsyncIterator:
  59. while True:
  60. next_input_message = await asyncio.wait_for(queue.get(), timeout)
  61. yield next_input_message
  62. if not next_input_message.uid and not next_input_message.tensors:
  63. break # this message means "done sending"
  64. def step(self, new_hidden_states: torch.Tensor):
  65. """Inference step: send a chunk of input tensors and receive a chunk of outputs"""
  66. if self.closed:
  67. raise Exception("Session is closed, cannot perform step")
  68. # serialize inputs and put them into the queue
  69. inputs = (new_hidden_states,)
  70. print('!!', self.uid)
  71. outputs_serialized = RemoteExpertWorker.run_coroutine(
  72. self._step(
  73. runtime_pb2.ExpertRequest(
  74. uid=self.uid,
  75. tensors=[
  76. serialize_torch_tensor(tensor, proto.compression)
  77. for tensor, proto in zip(inputs, nested_flatten(self.info["forward_schema"]))
  78. ],
  79. )
  80. )
  81. )
  82. outputs = list(map(deserialize_torch_tensor, outputs_serialized.tensors))
  83. assert outputs[0].shape == inputs[0].shape, f"expected outputs[0] to be hidden states but got {outputs[0]}"
  84. return outputs[0]
  85. async def _step(self, inputs_serialized: runtime_pb2.ExpertRequest) -> runtime_pb2.ExpertResponse:
  86. """Inference step on serialized data. This code is meant to be run inside RemoteExpertWorker"""
  87. await self._inputs_queue.put(inputs_serialized)
  88. self.stepped = True
  89. return await anext(self._outputs_stream)
  90. def close(self):
  91. """Finish a given inference session, close the underlying connection"""
  92. if self._outputs_stream is None:
  93. return # already closed
  94. RemoteExpertWorker.run_coroutine(self._aclose_stream())
  95. self._outputs_stream = self._inputs_queue = None
  96. self.closed = True
  97. async def _aclose_stream(self):
  98. """Close the inference session. This code is meant to be run inside RemoteExpertWorker"""
  99. if self._outputs_stream is None:
  100. return # already closed
  101. if self.stepped:
  102. await self._inputs_queue.put(runtime_pb2.ExpertRequest()) # empty request will trigger end of session
  103. try:
  104. await anext(self._outputs_stream)
  105. except StopAsyncIteration:
  106. pass
  107. def __del__(self):
  108. self.close()
  109. def __enter__(self):
  110. assert not self.closed
  111. return self
  112. def __exit__(self, *exc_details):
  113. self.close()