adaptive.py 12 KB

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