remote.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. from typing import Any, Dict, Optional, Tuple
  2. import torch
  3. import torch.nn as nn
  4. from hivemind.moe.client.remote_expert_worker import RemoteExpertWorker
  5. from torch.autograd.function import once_differentiable
  6. import hivemind
  7. from load_balancer import LoadBalancer
  8. from hivemind.moe.client.expert import DUMMY, expert_forward
  9. from hivemind.proto import runtime_pb2
  10. from hivemind.compression import serialize_torch_tensor, deserialize_torch_tensor
  11. from hivemind.utils import get_logger, nested_compare, nested_flatten, nested_pack
  12. logger = get_logger(__name__)
  13. class BalancedRemoteExpert(nn.Module):
  14. """
  15. A torch module that dynamically assigns weights to one RemoteExpert from a pool, proportionally to their throughput.
  16. ToDo docstring, similar to hivemind.RemoteExpert
  17. """
  18. def __init__(
  19. self,
  20. *,
  21. dht: hivemind.DHT,
  22. uid_prefix: str,
  23. grid_size: Tuple[int, ...],
  24. forward_timeout: Optional[float] = None,
  25. backward_timeout: Optional[float] = None,
  26. update_period: float = 30.0,
  27. backward_task_size_multiplier: float = 2.5,
  28. **kwargs,
  29. ):
  30. super().__init__()
  31. if uid_prefix.endswith(".0."):
  32. logger.warning(f"BalancedRemoteExperts will look for experts under prefix {self.uid_prefix}0.")
  33. assert len(grid_size) == 2 and grid_size[0] == 1, "only 1xN grids are supported"
  34. self.dht, self.uid_prefix, self.grid_size = dht, uid_prefix, grid_size
  35. self.forward_timeout, self.backward_timeout = forward_timeout, backward_timeout
  36. self.backward_task_size_multiplier = backward_task_size_multiplier
  37. self.expert_balancer = LoadBalancer(dht, key=f"{self.uid_prefix}0.", update_period=update_period, **kwargs)
  38. self._expert_info = None # expert['info'] from one of experts in the grid
  39. def forward(self, *args: torch.Tensor, **kwargs: torch.Tensor):
  40. """
  41. Call one of the RemoteExperts for the specified inputs and return output. Compatible with pytorch.autograd.
  42. :param args: input tensors that will be passed to each expert after input, batch-first
  43. :param kwargs: extra keyword tensors that will be passed to each expert, batch-first
  44. :returns: averaged predictions of all experts that delivered result on time, nested structure of batch-first
  45. """
  46. assert len(kwargs) == len(self.info["keyword_names"]), f"Keyword args should be {self.info['keyword_names']}"
  47. kwargs = {key: kwargs[key] for key in self.info["keyword_names"]}
  48. if self._expert_info is None:
  49. raise NotImplementedError()
  50. # Note: we put keyword arguments in the same order as on a server to prevent f(a=1, b=2) != f(b=2, a=1) errors
  51. forward_inputs = (args, kwargs)
  52. if not nested_compare(forward_inputs, self.info["forward_schema"]):
  53. raise TypeError(f"Inputs do not match expert input schema. Did you pass the right number of parameters?")
  54. flat_inputs = list(nested_flatten(forward_inputs))
  55. forward_task_size = flat_inputs[0].shape[0]
  56. # Note: we send DUMMY to prevent torch from excluding expert from backward if no other inputs require grad
  57. flat_outputs = _BalancedRemoteModuleCall.apply(DUMMY,
  58. self.expert_balancer,
  59. self.info,
  60. self.forward_timeout,
  61. self.backward_timeout,
  62. forward_task_size,
  63. forward_task_size * self.backward_task_size_multiplier,
  64. *flat_inputs)
  65. return nested_pack(flat_outputs, structure=self.info["outputs_schema"])
  66. @property
  67. def info(self):
  68. while self._expert_info is None:
  69. try:
  70. with self.expert_balancer.use_another_expert(1) as chosen_expert:
  71. self._expert_info = chosen_expert.info
  72. except BaseException as e:
  73. logger.error(f"Tried to get expert info from {chosen_expert} but caught {repr(e)}")
  74. return self._expert_info
  75. class _BalancedRemoteModuleCall(torch.autograd.Function):
  76. """Internal autograd-friendly call of a remote module. For applications, use BalancedRemoteExpert instead."""
  77. @staticmethod
  78. def forward(
  79. ctx,
  80. dummy: torch.Tensor,
  81. expert_balancer: LoadBalancer,
  82. info: Dict[str, Any],
  83. forward_timeout: float,
  84. backward_timeout: float,
  85. forward_task_size: float,
  86. backward_task_size: float,
  87. *inputs: torch.Tensor,
  88. ) -> Tuple[torch.Tensor, ...]:
  89. # Note: *inputs are flattened input tensors that follow the expert's info['input_schema']
  90. # detach to avoid pickling the computation graph
  91. ctx.expert_balancer, ctx.info = expert_balancer, info
  92. ctx.forward_timeout, ctx.backward_timeout = forward_timeout, backward_timeout
  93. ctx.forward_task_size, ctx.backward_task_size = forward_task_size, backward_task_size
  94. inputs = tuple(tensor.cpu().detach() for tensor in inputs)
  95. ctx.save_for_backward(*inputs)
  96. serialized_tensors = [
  97. serialize_torch_tensor(inp, proto.compression)
  98. for inp, proto in zip(inputs, nested_flatten(info["forward_schema"]))
  99. ]
  100. while True:
  101. try:
  102. with expert_balancer.use_another_expert(forward_task_size) as chosen_expert:
  103. deserialized_outputs = RemoteExpertWorker.run_coroutine(expert_forward(
  104. chosen_expert.uid, inputs, serialized_tensors, chosen_expert.stub))
  105. break
  106. except BaseException as e:
  107. logger.error(f"Tried to call forward for expert {chosen_expert} but caught {repr(e)}")
  108. return tuple(deserialized_outputs)
  109. @staticmethod
  110. @once_differentiable
  111. def backward(ctx, *grad_outputs) -> Tuple[Optional[torch.Tensor], ...]:
  112. raise NotImplementedError("Backward is not yet implemented in this example")
  113. # grad_outputs_cpu = tuple(tensor.cpu() for tensor in grad_outputs)
  114. # inputs_and_grad_outputs = tuple(nested_flatten((ctx.saved_tensors, grad_outputs_cpu)))
  115. # backward_schema = tuple(nested_flatten((ctx.info["forward_schema"], ctx.info["outputs_schema"])))
  116. # serialized_tensors = [
  117. # serialize_torch_tensor(tensor, proto.compression)
  118. # for tensor, proto in zip(inputs_and_grad_outputs, backward_schema)
  119. # ]
  120. # while True:
  121. # try:
  122. # with ctx.expert_balancer.use_another_expert(ctx.backward_task_size) as chosen_expert:
  123. # backward_request = runtime_pb2.ExpertRequest(uid=chosen_expert.uid, tensors=serialized_tensors)
  124. # grad_inputs = chosen_expert.stub.forward(backward_request, timeout=ctx.backward_timeout)
  125. # break
  126. # except BaseException as e:
  127. # logger.error(f"Tried to call backward for expert {chosen_expert} but caught {repr(e)}")
  128. # deserialized_grad_inputs = [deserialize_torch_tensor(tensor) for tensor in grad_inputs.tensors]
  129. # return (DUMMY, None, None, None, None, None, None, *deserialized_grad_inputs)