remote_block.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  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, get_logger, nested_flatten, use_hivemind_log_handler
  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.servers.keys()))) # 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 or v is False, 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,
  50. remote_module: RemoteTransformerBlock,
  51. timeout: Optional[float] = None,
  52. ) -> RemoteTransformerBlockInferenceSession:
  53. """Create a new session for a given remote module. This code is meant to be run inside RemoteExpertWorker"""
  54. inputs_queue = asyncio.Queue()
  55. outputs_stream = await remote_module.stub.rpc_inference(
  56. cls._read_inputs_from_queue(inputs_queue, timeout),
  57. timeout=timeout,
  58. )
  59. return cls(remote_module.uid, remote_module.info, inputs_queue, outputs_stream)
  60. @staticmethod
  61. async def _read_inputs_from_queue(queue: asyncio.Queue, timeout: Optional[float]) -> AsyncIterator:
  62. while True:
  63. next_input_message = await asyncio.wait_for(queue.get(), timeout)
  64. yield next_input_message
  65. if not next_input_message.uid and not next_input_message.tensors:
  66. break # this message means "done sending"
  67. def step(self, new_hidden_states: torch.Tensor):
  68. """Inference step: send a chunk of input tensors and receive a chunk of outputs"""
  69. if self.closed:
  70. raise Exception("Session is closed, cannot perform step")
  71. # serialize inputs and put them into the queue
  72. inputs = (new_hidden_states,)
  73. outputs_serialized = RemoteExpertWorker.run_coroutine(
  74. self._step(
  75. runtime_pb2.ExpertRequest(
  76. uid=self.uid,
  77. tensors=[
  78. serialize_torch_tensor(tensor, proto.compression)
  79. for tensor, proto in zip(inputs, nested_flatten(self.info["forward_schema"]))
  80. ],
  81. )
  82. )
  83. )
  84. outputs = list(map(deserialize_torch_tensor, outputs_serialized.tensors))
  85. assert outputs[0].shape == inputs[0].shape, f"expected outputs[0] to be hidden states but got {outputs[0]}"
  86. return outputs[0]
  87. async def _step(self, inputs_serialized: runtime_pb2.ExpertRequest) -> runtime_pb2.ExpertResponse:
  88. """Inference step on serialized data. This code is meant to be run inside RemoteExpertWorker"""
  89. await self._inputs_queue.put(inputs_serialized)
  90. self.stepped = True
  91. return await anext(self._outputs_stream)
  92. def close(self):
  93. """Finish a given inference session, close the underlying connection"""
  94. if self._outputs_stream is None:
  95. return # already closed
  96. RemoteExpertWorker.run_coroutine(self._aclose_stream())
  97. self._outputs_stream = self._inputs_queue = None
  98. self.closed = True
  99. async def _aclose_stream(self):
  100. """Close the inference session. This code is meant to be run inside RemoteExpertWorker"""
  101. if self._outputs_stream is None:
  102. return # already closed
  103. if self.stepped:
  104. await self._inputs_queue.put(runtime_pb2.ExpertRequest()) # empty request will trigger end of session
  105. try:
  106. await anext(self._outputs_stream)
  107. except StopAsyncIteration:
  108. pass
  109. def __del__(self):
  110. self.close()
  111. def __enter__(self):
  112. assert not self.closed
  113. return self
  114. def __exit__(self, *exc_details):
  115. self.close()