moe.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. import multiprocessing as mp
  2. import multiprocessing.pool
  3. from functools import partial
  4. from typing import Tuple, List, Dict, Any, Optional
  5. import numpy as np
  6. import torch
  7. import torch.nn as nn
  8. from torch.autograd.function import once_differentiable
  9. from .expert import RemoteExpert, _RemoteModuleCall
  10. from ..utils import nested_map, check_numpy, run_and_await_k, nested_pack, nested_flatten, DUMMY
  11. from ..utils.autograd import run_isolated_forward, EmulatedAutogradContext, run_isolated_backward
  12. class RemoteMixtureOfExperts(nn.Module):
  13. """
  14. A torch module that performs mixture of experts inference with a local gating function and multiple remote experts.
  15. Natively supports pytorch autograd.
  16. :note: By default, not all experts are guaranteed to perform forward pass. Moreover, not all of those who ran
  17. forward pass are guaranteed to perform backward pass. In the latter case, gradient will be averaged without
  18. the missing experts
  19. :param in_features: common input size for experts and gating function
  20. :param grid_size: tesseract dimensions that form expert uid (see below)
  21. :param uid_prefix: common prefix for all expert uids
  22. expert uid follows the pattern {uid_prefix}{0...grid_size[0]}.{0...grid_size[1]}...{0...grid_size[-1]}
  23. :param network: TesseractNetwork where the experts reside
  24. :param num_workers: number of threads for parallel network operation
  25. :param k_best: queries this many experts with highest scores
  26. :param k_min: makes sure at least this many experts returned output
  27. :param timeout_after_k_min: waits for this many seconds after k_min experts returned results.
  28. Any expert that didn't manage to return output after that delay is considered unavailable
  29. :param expert_padding: internal value used to denote "absent expert". Should not coincide with any expert uid.
  30. """
  31. def __init__(self, *, in_features, grid_size: Tuple[int], network, num_workers=None,
  32. k_best, k_min=1, timeout_after_k_min=1.0, uid_prefix='', expert_padding=None):
  33. super().__init__()
  34. self.network, self.grid_size = network, grid_size
  35. self.uid_prefix, self.expert_padding = uid_prefix, expert_padding
  36. self.k_best, self.k_min, self.timeout_after_k_min = k_best, k_min, timeout_after_k_min
  37. self.thread_pool = mp.pool.ThreadPool(num_workers or k_best * 2)
  38. self.proj = nn.Linear(in_features, sum(grid_size)) # jointly predict logits for all grid dimensions
  39. def forward(self, input: torch.Tensor, *args, **kwargs) -> Tuple[List[List[RemoteExpert]], torch.Tensor]:
  40. """
  41. Choose k best experts with beam search, then call chosen experts and average their outputs.
  42. :param batch: named tensors, each tensor has 0-th axis dedicated to batch (aka batch-first
  43. :returns: averaged predictions of all experts that delivered on time
  44. """
  45. assert len(input.shape) == 2
  46. # 1. compute scores and find most appropriate experts with beam search
  47. grid_scores = self.proj(input).split_with_sizes(self.grid_size, dim=-1)
  48. batch_experts = self.beam_search(grid_scores, self.k_best)
  49. # ^-- List[batch_size] of List[RemoteExpert] chosen for every input in batch
  50. # 2.1 call chosen experts (run them in background to save time)
  51. batch_outputs_async = [
  52. self.thread_pool.apply_async(self._run_experts,
  53. args=[chosen_experts, input[i: i + 1], *(tensor[i: i + 1] for tensor in args)],
  54. kwds={key: tensor[i: i + 1] for key, tensor in kwargs.items()})
  55. for i, chosen_experts in enumerate(batch_experts)
  56. ]
  57. # 2.2 compute *differentiable* logits for each expert
  58. batch_expert_logits = self._score_experts(grid_scores, batch_experts)
  59. # ^-- List[batch_size] of Dict[RemoteExpert, logit] before softmax for each active expert
  60. batch_outputs = []
  61. for output_async, expert_logits in zip(batch_outputs_async, batch_expert_logits):
  62. expert_outputs: Dict[RemoteExpert, Any] = output_async.get()
  63. flat_experts, flat_outputs = zip(*expert_outputs.items())
  64. # 3.1. normalize logits over only those experts that DID return output
  65. flat_logits = torch.stack([expert_logits[expert] for expert in flat_experts])
  66. flat_weights = torch.softmax(flat_logits, dim=-1)
  67. # 3.2. average each output across experts
  68. average_outputs = nested_map(
  69. lambda *tensors: sum(x * weight for x, weight in zip(tensors, flat_weights)), *flat_outputs)
  70. batch_outputs.append(average_outputs)
  71. # 4. concatenate mixture outputs from individual experts
  72. return nested_map(lambda *tensors: torch.cat(tensors, dim=0), *batch_outputs)
  73. def beam_search(self, grid_scores: List[torch.Tensor], k_best: int, **kwargs) -> List[List[RemoteExpert]]:
  74. """
  75. Find and return k best experts in the grid using (exact) beam search of the product space
  76. :param grid_scores: scores predicted for each dimension in the grid,
  77. :type grid_scores: a sequence of tensors of shape[batch_size, self.grid_size[i]]
  78. :param k_best: how many of the top experts participate in the computation
  79. :param kwargs: extra keyword parameters passed to self.network.first_k_active
  80. :returns: a list of *batch_size* lists that contain chosen experts for one sample each inner list contains \
  81. RemoteExpert instances for *up to* k_best experts
  82. """
  83. assert len(grid_scores) == len(self.grid_size)
  84. assert all(len(dim_scores.shape) == 2 for dim_scores in grid_scores)
  85. batch_size = len(grid_scores[0])
  86. beam = np.array([[self.uid_prefix]] * batch_size, dtype=object) # [batch_size, up_to_beam_size]
  87. scores = np.zeros([batch_size, 1], dtype=np.float64)
  88. delimeters = np.array(self.network.UID_DELIMETER)[None, None, None] # pre-compute numpy array for fast concat
  89. for dim_index, dim_scores in enumerate(grid_scores):
  90. dim_scores = check_numpy(dim_scores)
  91. assert dim_scores.shape[-1] == self.grid_size[dim_index]
  92. # create all possible successsors from current beam
  93. dim_indices = np.arange(dim_scores.shape[1]).astype(str)
  94. new_candidates = beam[:, :, None] + delimeters + dim_indices[None, None, :]
  95. new_candidates = new_candidates.reshape([batch_size, -1])
  96. new_scores = scores[:, :, None] + dim_scores[:, None, :]
  97. new_scores = new_scores.reshape([batch_size, -1])
  98. # select k best candidates according to scores but only those that are still active
  99. new_order = np.argsort(- new_scores, axis=-1)
  100. top_alive_lookups = [
  101. self.thread_pool.apply_async(self.network.first_k_active, args=(cands[order], k_best), kwds=kwargs)
  102. for cands, order in zip(new_candidates, new_order)]
  103. batch_cand_to_score = [
  104. dict(zip(cands, cand_scores)) for cands, cand_scores in zip(new_candidates, new_scores)]
  105. top_alive_prefixes = [result.get() for result in top_alive_lookups]
  106. top_alive_scores = [list(map(cand_to_score.get, top_cands))
  107. for cand_to_score, top_cands in zip(batch_cand_to_score, top_alive_prefixes)]
  108. # pad up to beam size
  109. beam = np.array([row + [self.expert_padding] * (k_best - len(row))
  110. for row in top_alive_prefixes], dtype='object')
  111. scores = np.array([row + [-float('inf')] * (k_best - len(row))
  112. for row in top_alive_scores], dtype='float32')
  113. unique_experts = self.network.get_experts(list(set(
  114. uid for row in beam for uid in row if uid != self.expert_padding)))
  115. unique_experts_by_uid = {expert.uid: expert for expert in unique_experts if expert != self.expert_padding}
  116. return [[unique_experts_by_uid[uid] for uid in row if uid in unique_experts_by_uid] for row in beam]
  117. def _score_experts(self, grid_scores: List[torch.Tensor],
  118. experts: List[List[RemoteExpert]]) -> List[Dict[RemoteExpert, torch.Tensor]]:
  119. flat_experts = [expert for row in experts for expert in row]
  120. flat_batch_indices = torch.tensor([i for i, row in enumerate(experts) for uid in range(len(row))])
  121. grid_indices = np.zeros([len(flat_experts), len(grid_scores)], dtype=np.int64)
  122. for i, expert in enumerate(flat_experts):
  123. expert_indices = expert.uid[len(self.uid_prefix) + len(self.network.UID_DELIMETER):]
  124. expert_indices = list(map(int, expert_indices.split(self.network.UID_DELIMETER)))
  125. grid_indices[i] = expert_indices
  126. scores_per_dim = [
  127. dim_scores[flat_batch_indices, dim_indices] if len(flat_batch_indices) else torch.zeros(0)
  128. for dim_scores, dim_indices in zip(grid_scores, grid_indices.T)]
  129. flat_scores = torch.sum(torch.stack(scores_per_dim, dim=0), dim=0)
  130. output_dicts = [dict() for _ in range(len(experts))]
  131. for batch_i, expert, score in zip(check_numpy(flat_batch_indices),
  132. flat_experts, flat_scores):
  133. output_dicts[batch_i][expert] = score
  134. return output_dicts
  135. class _RemoteMoECall(torch.autograd.Function):
  136. """
  137. Internal autograd-friendly function that calls multiple experts on the same input and averages their outputs.
  138. This function that can recover from individual failures during forward and/or backward passes.
  139. For user-friendly version of this function, use RemoteMixtureOfExperts module.
  140. """
  141. @classmethod
  142. def forward(cls, ctx, expert_logits: torch.Tensor, experts: List[RemoteExpert],
  143. k_min: int, timeout_after_k_min: float, backward_k_min: int, timeout_total: Optional[float],
  144. backward_timeout: Optional[float], input_schema, *flat_inputs: torch.Tensor) -> Tuple[torch.Tensor]:
  145. expert_args, expert_kwargs = nested_pack(flat_inputs, structure=input_schema)
  146. assert expert_logits.ndim == 1 and len(expert_logits) == len(experts)
  147. # 1. call experts and await results
  148. jobs = [partial(cls._run_expert_forward, expert, *expert_args, **expert_kwargs) for expert in experts]
  149. results = run_and_await_k(jobs, k=k_min, timeout_after_k=timeout_after_k_min, timeout_total=timeout_total)
  150. alive_contexts, alive_outputs, alive_ix = zip(*[(result[0], result[1], ix) for ix, result in enumerate(results)
  151. if not isinstance(result, BaseException)])
  152. # ^ ^ ^-- a list of indices of experts that returned outputs in time
  153. # \ \-- list of outputs of every expert that didn't die on us
  154. # \-- a list of autograd contexts, used for parallel backward
  155. # 2. compute softmax weights for alive experts and average outputs
  156. alive_ix = torch.as_tensor(alive_ix, device=expert_logits.device)
  157. alive_expert_probs = torch.softmax(expert_logits[alive_ix], dim=0)
  158. stacked_alive_outputs = tuple(map(torch.stack, zip(*alive_outputs)))
  159. flat_average_outputs = tuple(dot_along_first_axis(alive_expert_probs, stacked_out)
  160. for stacked_out in stacked_alive_outputs)
  161. # 3. save individual outputs for backward pass
  162. ctx.save_for_backward(expert_logits, alive_ix, alive_expert_probs, *stacked_alive_outputs)
  163. ctx._alive_contexts = alive_contexts
  164. ctx._backward_k_min = backward_k_min
  165. ctx._backward_timeout = backward_timeout
  166. return tuple(map(torch.Tensor.detach, flat_average_outputs))
  167. @classmethod
  168. @once_differentiable
  169. def backward(cls, ctx, *grad_outputs_flat: torch.Tensor) -> Tuple[Optional[torch.Tensor], ...]:
  170. """ Like normal backward, but we ignore any experts that failed during backward pass """
  171. expert_logits, alive_ix, alive_expert_probas, *stacked_alive_outputs = ctx.saved_tensors
  172. alive_contexts, k_min, timeout = ctx._alive_contexts, ctx._backward_k_min, ctx._backward_timeout
  173. jobs = [partial(cls._run_expert_backward, ctx, prob, *grad_outputs_flat)
  174. for ctx, prob in zip(alive_contexts, alive_expert_probas.split(1))]
  175. results = run_and_await_k(jobs, k=k_min, timeout_after_k=None, timeout_total=timeout)
  176. backward_survivors_in_alive_ix, survived_grad_inputs = zip(*((i, grads) for i, grads in enumerate(results)))
  177. backward_survivors_in_alive_ix = torch.as_tensor(backward_survivors_in_alive_ix, device=expert_logits.device)
  178. backward_survivors_ix = alive_ix[backward_survivors_in_alive_ix]
  179. survived_probas = torch.softmax(expert_logits[backward_survivors_ix], dim=0)
  180. weight_ratios = survived_probas / alive_expert_probas[backward_survivors_in_alive_ix]
  181. flat_grad_inputs = tuple(dot_along_first_axis(weight_ratios, stacked_grad_inp)
  182. for stacked_grad_inp in map(torch.stack, zip(*survived_grad_inputs)))
  183. # compute grad w.r.t. logits
  184. grad_wrt_probs = sum(tuple(
  185. torch.sum(grad_out[None, ...] * stacked_avive_out[backward_survivors_in_alive_ix],
  186. dim=tuple(range(1, stacked_avive_out.ndim)))
  187. for grad_out, stacked_avive_out in zip(grad_outputs_flat, stacked_alive_outputs)
  188. ))
  189. softmax_jacobian = torch.diagflat(survived_probas) - torch.ger(survived_probas, survived_probas)
  190. grad_wrt_logits = grad_wrt_probs @ softmax_jacobian
  191. return grad_wrt_logits, None, None, None, None, None, None, None, *flat_grad_inputs
  192. @staticmethod
  193. def _run_expert_forward(expert: RemoteExpert, *args: torch.Tensor, **kwargs: torch.Tensor):
  194. """ Call remote expert and return flattened outputs. Compatible with concurrent autograd. """
  195. flat_inputs = nested_flatten((args, kwargs))
  196. return run_isolated_forward(_RemoteModuleCall, DUMMY, expert.uid, expert.host, expert.port, *flat_inputs)
  197. @staticmethod
  198. def _run_expert_backward(ctx: EmulatedAutogradContext, weight: torch.Tensor, *grad_outputs: torch.Tensor):
  199. backward_result = run_isolated_backward(_RemoteModuleCall, ctx, *(grad * weight for grad in grad_outputs))
  200. grad_dummy, no_grad_uid, no_grad_hostname, no_grad_port, *grad_inputs = backward_result
  201. return grad_inputs
  202. def dot_along_first_axis(x, y):
  203. return (x.view(-1, *[1] * (y.ndim - 1)) * y).sum(0)