remote_moe.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. import multiprocessing as mp
  2. import multiprocessing.pool
  3. from concurrent.futures import Future, as_completed
  4. from functools import partial
  5. from typing import Tuple, List, Dict, Any
  6. import numpy as np
  7. import torch
  8. import torch.nn as nn
  9. from .remote_expert import RemoteExpert
  10. from ..utils import nested_map, check_numpy, run_in_background
  11. class RemoteMixtureOfExperts(nn.Module):
  12. """
  13. A torch module that performs mixture of experts inference with a local gating function and multiple remote experts.
  14. Natively supports pytorch autograd.
  15. :note: By default, not all experts are guaranteed to perform forward pass. Moreover, not all of those who ran
  16. forward pass are guaranteed to perform backward pass. In the latter case, gradient will be averaged without
  17. the missing experts
  18. :param in_features: common input size for experts and gating function
  19. :param grid_size: tesseract dimensions that form expert uid (see below)
  20. :param uid_prefix: common prefix for all expert uids
  21. expert uid follows the pattern {uid_prefix}{0...grid_size[0]}.{0...grid_size[1]}...{0...grid_size[-1]}
  22. :param network: TesseractNetwork where the experts reside
  23. :param num_workers: number of threads for parallel network operation
  24. :param k_best: queries this many experts with highest scores
  25. :param k_min: makes sure at least this many experts returned output
  26. :param timeout_after_k_min: waits for this many seconds after k_min experts returned results.
  27. Any expert that didn't manage to return output after that delay is considered unavailable
  28. :param expert_padding: internal value used to denote "absent expert". Should not coincide with any expert uid.
  29. """
  30. def __init__(self, *, in_features, grid_size: Tuple[int], network, num_workers=None,
  31. k_best, k_min=1, timeout_after_k_min=1.0, uid_prefix='', expert_padding=None):
  32. super().__init__()
  33. self.network, self.grid_size = network, grid_size
  34. self.uid_prefix, self.expert_padding = uid_prefix, expert_padding
  35. self.k_best, self.k_min, self.timeout_after_k_min = k_best, k_min, timeout_after_k_min
  36. self.thread_pool = mp.pool.ThreadPool(num_workers or k_best * 2)
  37. self.proj = nn.Linear(in_features, sum(grid_size)) # jointly predict logits for all grid dimensions
  38. def forward(self, input: torch.Tensor, *args, **kwargs) -> Tuple[List[List[RemoteExpert]], torch.Tensor]:
  39. """
  40. Choose k best experts with beam search, then call chosen experts and average their outputs.
  41. :param batch: named tensors, each tensor has 0-th axis dedicated to batch (aka batch-first
  42. :returns: averaged predictions of all experts that delivered on time
  43. """
  44. assert len(input.shape) == 2
  45. # 1. compute scores and find most appropriate experts with beam search
  46. grid_scores = self.proj(input).split_with_sizes(self.grid_size, dim=-1)
  47. batch_experts = self.beam_search(grid_scores, self.k_best)
  48. # ^-- List[batch_size] of List[RemoteExpert] chosen for every input in batch
  49. # 2.1 call chosen experts (run them in background to save time)
  50. batch_outputs_async = [
  51. self.thread_pool.apply_async(self._run_experts,
  52. args=[chosen_experts, input[i: i + 1], *(tensor[i: i + 1] for tensor in args)],
  53. kwds={key: tensor[i: i + 1] for key, tensor in kwargs.items()})
  54. for i, chosen_experts in enumerate(batch_experts)
  55. ]
  56. # 2.2 compute *differentiable* logits for each expert
  57. batch_expert_logits = self._score_experts(grid_scores, batch_experts)
  58. # ^-- List[batch_size] of Dict[RemoteExpert, logit] before softmax for each active expert
  59. batch_outputs = []
  60. for output_async, expert_logits in zip(batch_outputs_async, batch_expert_logits):
  61. expert_outputs: Dict[RemoteExpert, Any] = output_async.get()
  62. flat_experts, flat_outputs = zip(*expert_outputs.items())
  63. # 3.1. normalize logits over only those experts that DID return output
  64. flat_logits = torch.stack([expert_logits[expert] for expert in flat_experts])
  65. flat_weights = torch.softmax(flat_logits, dim=-1)
  66. # 3.2. average each output across experts
  67. average_outputs = nested_map(
  68. lambda *tensors: sum(x * weight for x, weight in zip(tensors, flat_weights)), *flat_outputs)
  69. batch_outputs.append(average_outputs)
  70. # 4. concatenate mixture outputs from individual experts
  71. return nested_map(lambda *tensors: torch.cat(tensors, dim=0), *batch_outputs)
  72. def beam_search(self, grid_scores: List[torch.Tensor], k_best: int, **kwargs) -> List[List[RemoteExpert]]:
  73. """
  74. Find and return k best experts in the grid using (exact) beam search of the product space
  75. :param grid_scores: scores predicted for each dimension in the grid,
  76. :type grid_scores: a sequence of tensors of shape[batch_size, self.grid_size[i]]
  77. :param k_best: how many of the top experts participate in the computation
  78. :param kwargs: extra keyword parameters passed to self.network.first_k_active
  79. :returns: a list of *batch_size* lists that contain chosen experts for one sample each inner list contains \
  80. RemoteExpert instances for *up to* k_best experts
  81. """
  82. assert len(grid_scores) == len(self.grid_size)
  83. assert all(len(dim_scores.shape) == 2 for dim_scores in grid_scores)
  84. batch_size = len(grid_scores[0])
  85. beam = np.array([[self.uid_prefix]] * batch_size, dtype=object) # [batch_size, up_to_beam_size]
  86. scores = np.zeros([batch_size, 1], dtype=np.float64)
  87. delimeters = np.array(self.network.UID_DELIMETER)[None, None, None] # pre-compute numpy array for fast concat
  88. for dim_index, dim_scores in enumerate(grid_scores):
  89. dim_scores = check_numpy(dim_scores)
  90. assert dim_scores.shape[-1] == self.grid_size[dim_index]
  91. # create all possible successsors from current beam
  92. dim_indices = np.arange(dim_scores.shape[1]).astype(str)
  93. new_candidates = beam[:, :, None] + delimeters + dim_indices[None, None, :]
  94. new_candidates = new_candidates.reshape([batch_size, -1])
  95. new_scores = scores[:, :, None] + dim_scores[:, None, :]
  96. new_scores = new_scores.reshape([batch_size, -1])
  97. # select k best candidates according to scores but only those that are still active
  98. new_order = np.argsort(- new_scores, axis=-1)
  99. top_alive_lookups = [
  100. self.thread_pool.apply_async(self.network.first_k_active, args=(cands[order], k_best), kwds=kwargs)
  101. for cands, order in zip(new_candidates, new_order)]
  102. batch_cand_to_score = [
  103. dict(zip(cands, cand_scores)) for cands, cand_scores in zip(new_candidates, new_scores)]
  104. top_alive_prefixes = [result.get() for result in top_alive_lookups]
  105. top_alive_scores = [list(map(cand_to_score.get, top_cands))
  106. for cand_to_score, top_cands in zip(batch_cand_to_score, top_alive_prefixes)]
  107. # pad up to beam size
  108. beam = np.array([row + [self.expert_padding] * (k_best - len(row))
  109. for row in top_alive_prefixes], dtype='object')
  110. scores = np.array([row + [-float('inf')] * (k_best - len(row))
  111. for row in top_alive_scores], dtype='float32')
  112. unique_experts = self.network.get_experts(list(set(
  113. uid for row in beam for uid in row if uid != self.expert_padding)))
  114. unique_experts_by_uid = {expert.uid: expert for expert in unique_experts if expert != self.expert_padding}
  115. return [
  116. [unique_experts_by_uid[uid] for uid in row if uid in unique_experts_by_uid]
  117. for row in beam]
  118. def _run_experts(self, experts: List[RemoteExpert], *args, **kwargs) -> Dict[RemoteExpert, torch.Tensor]:
  119. future_to_expert = {run_in_background(expert, *args, **kwargs): expert for expert in experts}
  120. pending_futures = set(future_to_expert.keys())
  121. outputs = {} # {expert -> output}
  122. # await first k futures for as long as it takes
  123. for future in as_completed(list(pending_futures), timeout=None):
  124. pending_futures.remove(future)
  125. if not future.exception():
  126. outputs[future_to_expert.pop(future)] = future.result()
  127. if len(outputs) > self.k_min:
  128. break
  129. # await stragglers for at most self.timeout_after_k_min
  130. for future in as_completed(pending_futures, timeout=self.timeout_after_k_min):
  131. if not future.exception():
  132. outputs[future_to_expert.pop(future)] = future.result()
  133. return outputs
  134. def _score_experts(self, grid_scores: List[torch.Tensor],
  135. experts: List[List[RemoteExpert]]) -> List[Dict[RemoteExpert, torch.Tensor]]:
  136. flat_experts = [expert for row in experts for expert in row]
  137. flat_batch_indices = torch.tensor([i for i, row in enumerate(experts) for uid in range(len(row))])
  138. grid_indices = np.zeros([len(flat_experts), len(grid_scores)], dtype=np.int64)
  139. for i, expert in enumerate(flat_experts):
  140. expert_indices = expert.uid[len(self.uid_prefix) + len(self.network.UID_DELIMETER):]
  141. expert_indices = list(map(int, expert_indices.split(self.network.UID_DELIMETER)))
  142. grid_indices[i] = expert_indices
  143. scores_per_dim = [
  144. dim_scores[flat_batch_indices, dim_indices] if len(flat_batch_indices) else torch.zeros(0)
  145. for dim_scores, dim_indices in zip(grid_scores, grid_indices.T)]
  146. flat_scores = torch.sum(torch.stack(scores_per_dim, dim=0), dim=0)
  147. output_dicts = [dict() for _ in range(len(experts))]
  148. for batch_i, expert, score in zip(check_numpy(flat_batch_indices),
  149. flat_experts, flat_scores):
  150. output_dicts[batch_i][expert] = score
  151. return output_dicts