adaptive.py 12 KB

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