adaptive.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. # mypy: allow-untyped-defs
  2. from collections import namedtuple
  3. import torch
  4. from torch import Tensor
  5. from typing import List, Sequence
  6. from . import Sequential, ModuleList, Linear
  7. from .module import Module
  8. from ..functional import log_softmax
  9. __all__ = ['AdaptiveLogSoftmaxWithLoss']
  10. _ASMoutput = namedtuple('_ASMoutput', ['output', 'loss'])
  11. class AdaptiveLogSoftmaxWithLoss(Module):
  12. r"""Efficient softmax approximation.
  13. As described in
  14. `Efficient softmax approximation for GPUs by Edouard Grave, Armand Joulin,
  15. Moustapha Ciss\u00e9, David Grangier, and Herv\u00e9 J\u00e9gou
  16. <https://arxiv.org/abs/1609.04309>`__.
  17. Adaptive softmax is an approximate strategy for training models with large
  18. output spaces. It is most effective when the label distribution is highly
  19. imbalanced, for example in natural language modelling, where the word
  20. frequency distribution approximately follows the `Zipf's law`_.
  21. Adaptive softmax partitions the labels into several clusters, according to
  22. their frequency. These clusters may contain different number of targets
  23. each.
  24. Additionally, clusters containing less frequent labels assign lower
  25. dimensional embeddings to those labels, which speeds up the computation.
  26. For each minibatch, only clusters for which at least one target is
  27. present are evaluated.
  28. The idea is that the clusters which are accessed frequently
  29. (like the first one, containing most frequent labels), should also be cheap
  30. to compute -- that is, contain a small number of assigned labels.
  31. We highly recommend taking a look at the original paper for more details.
  32. * :attr:`cutoffs` should be an ordered Sequence of integers sorted
  33. in the increasing order.
  34. It controls number of clusters and the partitioning of targets into
  35. clusters. For example setting ``cutoffs = [10, 100, 1000]``
  36. means that first `10` targets will be assigned
  37. to the 'head' of the adaptive softmax, targets `11, 12, ..., 100` will be
  38. assigned to the first cluster, and targets `101, 102, ..., 1000` will be
  39. assigned to the second cluster, while targets
  40. `1001, 1002, ..., n_classes - 1` will be assigned
  41. to the last, third cluster.
  42. * :attr:`div_value` is used to compute the size of each additional cluster,
  43. which is given as
  44. :math:`\left\lfloor\frac{\texttt{in\_features}}{\texttt{div\_value}^{idx}}\right\rfloor`,
  45. where :math:`idx` is the cluster index (with clusters
  46. for less frequent words having larger indices,
  47. and indices starting from :math:`1`).
  48. * :attr:`head_bias` if set to True, adds a bias term to the 'head' of the
  49. adaptive softmax. See paper for details. Set to False in the official
  50. implementation.
  51. .. warning::
  52. Labels passed as inputs to this module should be sorted according to
  53. their frequency. This means that the most frequent label should be
  54. represented by the index `0`, and the least frequent
  55. label should be represented by the index `n_classes - 1`.
  56. .. note::
  57. This module returns a ``NamedTuple`` with ``output``
  58. and ``loss`` fields. See further documentation for details.
  59. .. note::
  60. To compute log-probabilities for all classes, the ``log_prob``
  61. method can be used.
  62. Args:
  63. in_features (int): Number of features in the input tensor
  64. n_classes (int): Number of classes in the dataset
  65. cutoffs (Sequence): Cutoffs used to assign targets to their buckets
  66. div_value (float, optional): value used as an exponent to compute sizes
  67. of the clusters. Default: 4.0
  68. head_bias (bool, optional): If ``True``, adds a bias term to the 'head' of the
  69. adaptive softmax. Default: ``False``
  70. Returns:
  71. ``NamedTuple`` with ``output`` and ``loss`` fields:
  72. * **output** is a Tensor of size ``N`` containing computed target
  73. log probabilities for each example
  74. * **loss** is a Scalar representing the computed negative
  75. log likelihood loss
  76. Shape:
  77. - input: :math:`(N, \texttt{in\_features})` or :math:`(\texttt{in\_features})`
  78. - target: :math:`(N)` or :math:`()` where each value satisfies :math:`0 <= \texttt{target[i]} <= \texttt{n\_classes}`
  79. - output1: :math:`(N)` or :math:`()`
  80. - output2: ``Scalar``
  81. .. _Zipf's law: https://en.wikipedia.org/wiki/Zipf%27s_law
  82. """
  83. in_features: int
  84. n_classes: int
  85. cutoffs: List[int]
  86. div_value: float
  87. head_bias: bool
  88. head: Linear
  89. tail: ModuleList
  90. def __init__(
  91. self,
  92. in_features: int,
  93. n_classes: int,
  94. cutoffs: Sequence[int],
  95. div_value: float = 4.,
  96. head_bias: bool = False,
  97. device=None,
  98. dtype=None
  99. ) -> None:
  100. factory_kwargs = {'device': device, 'dtype': dtype}
  101. super().__init__()
  102. cutoffs = list(cutoffs)
  103. if (len(cutoffs) == 0):
  104. raise ValueError("cutoffs should be a sequence of length larger than 0")
  105. if (cutoffs != sorted(cutoffs)) \
  106. or (min(cutoffs) <= 0) \
  107. or (max(cutoffs) > (n_classes - 1)) \
  108. or (len(set(cutoffs)) != len(cutoffs)) \
  109. or any(int(c) != c for c in cutoffs):
  110. raise ValueError("cutoffs should be a sequence of unique, positive "
  111. "integers sorted in an increasing order, where "
  112. "each value is between 1 and n_classes-1")
  113. self.in_features = in_features
  114. self.n_classes = n_classes
  115. self.cutoffs = cutoffs + [n_classes]
  116. self.div_value = div_value
  117. self.head_bias = head_bias
  118. self.shortlist_size = self.cutoffs[0]
  119. self.n_clusters = len(self.cutoffs) - 1
  120. self.head_size = self.shortlist_size + self.n_clusters
  121. self.head = Linear(self.in_features, self.head_size, bias=self.head_bias,
  122. **factory_kwargs)
  123. self.tail = ModuleList()
  124. for i in range(self.n_clusters):
  125. hsz = int(self.in_features // (self.div_value ** (i + 1)))
  126. osz = self.cutoffs[i + 1] - self.cutoffs[i]
  127. projection = Sequential(
  128. Linear(self.in_features, hsz, bias=False, **factory_kwargs),
  129. Linear(hsz, osz, bias=False, **factory_kwargs),
  130. )
  131. self.tail.append(projection)
  132. def reset_parameters(self) -> None:
  133. self.head.reset_parameters()
  134. for i2h, h2o in self.tail:
  135. i2h.reset_parameters()
  136. h2o.reset_parameters()
  137. def forward(self, input_: Tensor, target_: Tensor) -> _ASMoutput:
  138. targ_dim = target_.dim()
  139. if targ_dim == 1:
  140. if input_.size(0) != target_.size(0):
  141. raise RuntimeError('Input and target should have the same size '
  142. 'in the batch dimension.')
  143. if input_.dim() != 2:
  144. raise RuntimeError('1D target tensor expects 2D input tensors, '
  145. 'but found inputs with size', input_.size())
  146. elif targ_dim == 0:
  147. if input_.dim() != 1:
  148. raise RuntimeError('0D target tensor expects 1D input tensors, '
  149. 'but found inputs with size', input_.size())
  150. else:
  151. raise RuntimeError('0D or 1D target tensor expected, '
  152. 'multi-target not supported')
  153. is_batched = targ_dim > 0
  154. input = input_ if is_batched else input_.unsqueeze(0)
  155. target = target_ if is_batched else target_.unsqueeze(0)
  156. used_rows = 0
  157. batch_size = target.size(0)
  158. output = input.new_zeros(batch_size)
  159. gather_inds = target.new_empty(batch_size)
  160. cutoff_values = [0] + self.cutoffs
  161. for i in range(len(cutoff_values) - 1):
  162. low_idx = cutoff_values[i]
  163. high_idx = cutoff_values[i + 1]
  164. target_mask = (target >= low_idx) & (target < high_idx)
  165. row_indices = target_mask.nonzero().squeeze()
  166. if row_indices.numel() == 0:
  167. continue
  168. if i == 0:
  169. gather_inds.index_copy_(0, row_indices, target[target_mask])
  170. else:
  171. relative_target = target[target_mask] - low_idx
  172. input_subset = input.index_select(0, row_indices)
  173. cluster_output = self.tail[i - 1](input_subset)
  174. cluster_index = self.shortlist_size + i - 1
  175. gather_inds.index_fill_(0, row_indices, cluster_index)
  176. cluster_logprob = log_softmax(cluster_output, dim=1)
  177. local_logprob = cluster_logprob.gather(1, relative_target.unsqueeze(1))
  178. output.index_copy_(0, row_indices, local_logprob.squeeze(1))
  179. used_rows += row_indices.numel()
  180. if used_rows != batch_size:
  181. raise RuntimeError(f"Target values should be in [0, {self.n_classes - 1}], "
  182. f"but values in range [{target.min().item()}, {target.max().item()}] "
  183. "were found. ")
  184. head_output = self.head(input)
  185. head_logprob = log_softmax(head_output, dim=1)
  186. output += head_logprob.gather(1, gather_inds.unsqueeze(1)).squeeze()
  187. loss = (-output).mean()
  188. if not is_batched:
  189. output = output.squeeze(0)
  190. return _ASMoutput(output, loss)
  191. def _get_full_log_prob(self, input, head_output):
  192. """Given input tensor, and output of ``self.head``, compute the log of the full distribution."""
  193. out = input.new_empty((head_output.size(0), self.n_classes))
  194. head_logprob = log_softmax(head_output, dim=1)
  195. out[:, :self.shortlist_size] = head_logprob[:, :self.shortlist_size]
  196. for i, (start_idx, stop_idx) in enumerate(zip(self.cutoffs, self.cutoffs[1:])):
  197. cluster_output = self.tail[i](input)
  198. cluster_logprob = log_softmax(cluster_output, dim=1)
  199. output_logprob = cluster_logprob + head_logprob[:, self.shortlist_size + i].unsqueeze(1)
  200. out[:, start_idx:stop_idx] = output_logprob
  201. return out
  202. def log_prob(self, input: Tensor) -> Tensor:
  203. r"""Compute log probabilities for all :math:`\texttt{n\_classes}`.
  204. Args:
  205. input (Tensor): a minibatch of examples
  206. Returns:
  207. log-probabilities of for each class :math:`c`
  208. in range :math:`0 <= c <= \texttt{n\_classes}`, where :math:`\texttt{n\_classes}` is a
  209. parameter passed to ``AdaptiveLogSoftmaxWithLoss`` constructor.
  210. Shape:
  211. - Input: :math:`(N, \texttt{in\_features})`
  212. - Output: :math:`(N, \texttt{n\_classes})`
  213. """
  214. head_output = self.head(input)
  215. return self._get_full_log_prob(input, head_output)
  216. def predict(self, input: Tensor) -> Tensor:
  217. r"""Return the class with the highest probability for each example in the input minibatch.
  218. This is equivalent to ``self.log_prob(input).argmax(dim=1)``, but is more efficient in some cases.
  219. Args:
  220. input (Tensor): a minibatch of examples
  221. Returns:
  222. output (Tensor): a class with the highest probability for each example
  223. Shape:
  224. - Input: :math:`(N, \texttt{in\_features})`
  225. - Output: :math:`(N)`
  226. """
  227. head_output = self.head(input)
  228. output = torch.argmax(head_output, dim=1)
  229. not_in_shortlist = (output >= self.shortlist_size)
  230. all_in_shortlist = not (not_in_shortlist.any())
  231. if all_in_shortlist:
  232. return output
  233. elif not_in_shortlist.all():
  234. log_prob = self._get_full_log_prob(input, head_output)
  235. return torch.argmax(log_prob, dim=1)
  236. else:
  237. log_prob = self._get_full_log_prob(input[not_in_shortlist],
  238. head_output[not_in_shortlist])
  239. output[not_in_shortlist] = torch.argmax(log_prob, dim=1)
  240. return output