adaptive.py 12 KB

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