gating_function.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. import multiprocessing as mp
  2. import multiprocessing.pool
  3. from functools import partial
  4. from typing import Tuple, List, Dict, Any
  5. import numpy as np
  6. import torch
  7. import torch.nn as nn
  8. from .remote_expert import RemoteExpert
  9. from ..utils import nested_map, check_numpy, run_and_await_k
  10. class GatingFunction(nn.Module):
  11. def __init__(self, *, in_features, grid_size: Tuple[int], network, num_workers=None,
  12. k_best, k_min=1, timeout_after_k_min=1.0, uid_prefix='', expert_padding=None):
  13. super().__init__()
  14. self.network, self.grid_size = network, grid_size
  15. self.uid_prefix, self.expert_padding = uid_prefix, expert_padding
  16. self.k_best, self.k_min, self.timeout_after_k_min = k_best, k_min, timeout_after_k_min
  17. self.thread_pool = mp.pool.ThreadPool(num_workers or k_best * 2)
  18. self.proj = nn.Linear(in_features, sum(grid_size)) # jointly predict logits for all grid dimensions
  19. def forward(self, input: torch.Tensor, *args, **kwargs) -> Tuple[List[List[RemoteExpert]], torch.Tensor]:
  20. """
  21. Choose k best experts with beam search, then call chosen experts and average their outputs.
  22. :param batch: named tensors, each tensor has 0-th axis dedicated to batch (aka batch-first
  23. :return: averaged predictions of all experts that delivered on time
  24. """
  25. assert len(input.shape) == 2
  26. # 1. compute scores and find most appropriate experts with beam search
  27. grid_scores = self.proj(input).split_with_sizes(self.grid_size, dim=-1)
  28. batch_experts = self.beam_search(grid_scores, self.k_best)
  29. # ^-- List[batch_size] of List[RemoteExpert] chosen for every input in batch
  30. # 2.1 call chosen experts (run them in background to save time)
  31. batch_outputs_async = [
  32. self.thread_pool.apply_async(self._run_experts,
  33. args=[chosen_experts, input[i: i + 1], *(tensor[i: i + 1] for tensor in args)],
  34. kwds={key: tensor[i: i + 1] for key, tensor in kwargs.items()})
  35. for i, chosen_experts in enumerate(batch_experts)
  36. ]
  37. # 2.2 compute *differentiable* logits for each expert
  38. batch_expert_logits = self._score_experts(grid_scores, batch_experts)
  39. # ^-- List[batch_size] of Dict[RemoteExpert, logit] before softmax for each active expert
  40. batch_outputs = []
  41. for output_async, expert_logits in zip(batch_outputs_async, batch_expert_logits):
  42. expert_outputs: Dict[RemoteExpert, Any] = output_async.get()
  43. flat_experts, flat_outputs = zip(*expert_outputs.items())
  44. # 3.1. normalize logits over only those experts that DID return output
  45. flat_logits = torch.stack([expert_logits[expert] for expert in flat_experts])
  46. flat_weights = torch.softmax(flat_logits, dim=-1)
  47. # 3.2. average each output across experts
  48. average_outputs = nested_map(
  49. lambda *tensors: sum(x * weight for x, weight in zip(tensors, flat_weights)), *flat_outputs)
  50. batch_outputs.append(average_outputs)
  51. # 4. concatenate mixture outputs from individual experts
  52. return nested_map(lambda *tensors: torch.cat(tensors, dim=0), *batch_outputs)
  53. def beam_search(self, grid_scores: List[torch.Tensor], k_best: int, **kwargs) -> List[List[RemoteExpert]]:
  54. """
  55. Find and return k best experts in the grid using (exact) beam search of the product space
  56. :param grid_scores: scores predicted for each dimension in the grid,
  57. :type grid_scores: a sequence of tensors of shape[batch_size, self.grid_size[i]]
  58. :param k_best: how many of the top experts participate in the computation
  59. :param kwargs: extra keyword parameters passed to self.network.first_k_active
  60. :returns: a list of *batch_size* lists that contain chosen experts for one sample
  61. each inner list contains RemoteExpert instances for *up to* k_best experts
  62. """
  63. assert len(grid_scores) == len(self.grid_size)
  64. assert all(len(dim_scores.shape) == 2 for dim_scores in grid_scores)
  65. batch_size = len(grid_scores[0])
  66. beam = np.array([[self.uid_prefix]] * batch_size, dtype=object) # [batch_size, up_to_beam_size]
  67. scores = np.zeros([batch_size, 1], dtype=np.float64)
  68. delimeters = np.array(self.network.UID_DELIMETER)[None, None, None] # pre-compute numpy array for fast concat
  69. for dim_index, dim_scores in enumerate(grid_scores):
  70. dim_scores = check_numpy(dim_scores)
  71. assert dim_scores.shape[-1] == self.grid_size[dim_index]
  72. # create all possible successsors from current beam
  73. dim_indices = np.arange(dim_scores.shape[1]).astype(str)
  74. new_candidates = beam[:, :, None] + delimeters + dim_indices[None, None, :]
  75. new_candidates = new_candidates.reshape([batch_size, -1])
  76. new_scores = scores[:, :, None] + dim_scores[:, None, :]
  77. new_scores = new_scores.reshape([batch_size, -1])
  78. # select k best candidates according to scores but only those that are still active
  79. new_order = np.argsort(- new_scores, axis=-1)
  80. top_alive_lookups = [
  81. self.thread_pool.apply_async(self.network.first_k_active, args=(cands[order], k_best), kwds=kwargs)
  82. for cands, order in zip(new_candidates, new_order)]
  83. batch_cand_to_score = [
  84. dict(zip(cands, cand_scores)) for cands, cand_scores in zip(new_candidates, new_scores)]
  85. top_alive_prefixes = [result.get() for result in top_alive_lookups]
  86. top_alive_scores = [list(map(cand_to_score.get, top_cands))
  87. for cand_to_score, top_cands in zip(batch_cand_to_score, top_alive_prefixes)]
  88. # pad up to beam size
  89. beam = np.array([row + [self.expert_padding] * (k_best - len(row))
  90. for row in top_alive_prefixes], dtype='object')
  91. scores = np.array([row + [-float('inf')] * (k_best - len(row))
  92. for row in top_alive_scores], dtype='float32')
  93. unique_experts = self.network.get_experts(list(set(
  94. uid for row in beam for uid in row if uid != self.expert_padding)))
  95. unique_experts_by_uid = {expert.uid: expert for expert in unique_experts if expert != self.expert_padding}
  96. return [
  97. [unique_experts_by_uid[uid] for uid in row if uid in unique_experts_by_uid]
  98. for row in beam]
  99. def _run_experts(self, experts: List[RemoteExpert], *args, **kwargs) -> Dict[RemoteExpert, torch.Tensor]:
  100. outputs = run_and_await_k([partial(expert, *args, **kwargs) for expert in experts],
  101. k=self.k_min, timeout_after_k=self.timeout_after_k_min)
  102. return {expert: output for expert, output in zip(experts, outputs)
  103. if not isinstance(output, BaseException)}
  104. def _score_experts(self, grid_scores: List[torch.Tensor],
  105. experts: List[List[RemoteExpert]]) -> List[Dict[RemoteExpert, torch.Tensor]]:
  106. flat_experts = [expert for row in experts for expert in row]
  107. flat_batch_indices = torch.tensor([i for i, row in enumerate(experts)
  108. for uid in range(len(row))])
  109. grid_indices = np.zeros([len(flat_experts), len(grid_scores)], dtype=np.int64)
  110. for i, expert in enumerate(flat_experts):
  111. expert_indices = expert.uid[len(self.uid_prefix) + len(self.network.UID_DELIMETER):]
  112. expert_indices = list(map(int, expert_indices.split(self.network.UID_DELIMETER)))
  113. grid_indices[i] = expert_indices
  114. scores_per_dim = [
  115. dim_scores[flat_batch_indices, dim_indices] if len(flat_batch_indices) else torch.zeros(0)
  116. for dim_scores, dim_indices in zip(grid_scores, grid_indices.T)]
  117. flat_scores = torch.sum(torch.stack(scores_per_dim, dim=0), dim=0)
  118. output_dicts = [dict() for _ in range(len(experts))]
  119. for batch_i, expert, score in zip(check_numpy(flat_batch_indices),
  120. flat_experts, flat_scores):
  121. output_dicts[batch_i][expert] = score
  122. return output_dicts