|
| 1 | +from collections.abc import Callable |
| 2 | + |
| 3 | +import torch |
| 4 | +import torch.nn.functional as F |
| 5 | + |
| 6 | +from ignite.exceptions import NotComputableError |
| 7 | +from ignite.metrics.metric import Metric, reinit__is_reduced, sync_all_reduce |
| 8 | + |
| 9 | +__all__ = ["Perplexity"] |
| 10 | + |
| 11 | + |
| 12 | +class Perplexity(Metric): |
| 13 | + r"""Calculates the `Perplexity <https://en.wikipedia.org/wiki/Perplexity>`_ of a language model. |
| 14 | +
|
| 15 | + .. math:: |
| 16 | + \text{PPL}(W) = \exp \left( -\frac{1}{N} \sum_{i=1}^{N} \log P(w_i | w_1, \ldots, w_{i-1}) \right) |
| 17 | +
|
| 18 | + where :math:`N` is the total number of tokens and :math:`P(w_i | w_1, \ldots, w_{i-1})` is the |
| 19 | + conditional probability of token :math:`w_i` given the preceding tokens. |
| 20 | +
|
| 21 | + Perplexity is computed as :math:`\exp(\text{NLL})` where NLL is the mean negative log-likelihood |
| 22 | + over all tokens. Lower perplexity indicates a better language model. |
| 23 | +
|
| 24 | + - ``update`` must receive output of the form ``(y_pred, y)`` or ``{'y_pred': y_pred, 'y': y}``. |
| 25 | + - `y_pred` must be a floating-point tensor of shape ``(batch_size, vocab_size, seq_len)`` |
| 26 | + containing the unnormalized log-probabilities (logits). |
| 27 | + - `y` must be a long tensor of shape ``(batch_size, seq_len)`` containing the target token indices. |
| 28 | +
|
| 29 | + Note: |
| 30 | + Perplexity uses token-weighted accumulation rather than batch-average to avoid bias |
| 31 | + towards shorter sequences. The total NLL and total token count are accumulated across |
| 32 | + all batches, and the final perplexity is computed as ``exp(total_nll / total_tokens)``. |
| 33 | +
|
| 34 | + Args: |
| 35 | + output_transform: a callable that is used to transform the |
| 36 | + :class:`~ignite.engine.engine.Engine`'s ``process_function``'s output into the |
| 37 | + form expected by the metric. This can be useful if, for example, you have a multi-output model and |
| 38 | + you want to compute the metric with respect to one of the outputs. |
| 39 | + By default, metrics require the output as ``(y_pred, y)`` or ``{'y_pred': y_pred, 'y': y}``. |
| 40 | + device: specifies which device updates are accumulated on. Setting the |
| 41 | + metric's device to be the same as your ``update`` arguments ensures the ``update`` method is |
| 42 | + non-blocking. By default, CPU. |
| 43 | +
|
| 44 | + Examples: |
| 45 | +
|
| 46 | + For more information on how metric works with :class:`~ignite.engine.engine.Engine`, visit :ref:`attach-engine`. |
| 47 | +
|
| 48 | + .. testcode:: |
| 49 | +
|
| 50 | + from ignite.metrics.nlp import Perplexity |
| 51 | + import torch |
| 52 | +
|
| 53 | + ppl = Perplexity() |
| 54 | +
|
| 55 | + # batch_size=2, vocab_size=5, seq_len=3 |
| 56 | + y_pred = torch.log_softmax(torch.randn(2, 5, 3), dim=1) |
| 57 | + y = torch.randint(0, 5, (2, 3)) |
| 58 | +
|
| 59 | + ppl.update((y_pred, y)) |
| 60 | +
|
| 61 | + print(type(ppl.compute())) |
| 62 | +
|
| 63 | + .. testoutput:: |
| 64 | +
|
| 65 | + <class 'float'> |
| 66 | +
|
| 67 | + .. versionadded:: 0.5.2 |
| 68 | + """ |
| 69 | + |
| 70 | + _state_dict_all_req_keys = ("_sum_of_nll", "_num_tokens") |
| 71 | + |
| 72 | + def __init__( |
| 73 | + self, |
| 74 | + output_transform: Callable = lambda x: x, |
| 75 | + device: str | torch.device = torch.device("cpu"), |
| 76 | + ): |
| 77 | + super().__init__(output_transform=output_transform, device=device) |
| 78 | + |
| 79 | + @reinit__is_reduced |
| 80 | + def reset(self) -> None: |
| 81 | + self._sum_of_nll = torch.tensor(0.0, dtype=torch.double, device=self._device) |
| 82 | + self._num_tokens = torch.tensor(0, dtype=torch.long, device=self._device) |
| 83 | + |
| 84 | + @reinit__is_reduced |
| 85 | + def update(self, output: tuple[torch.Tensor, torch.Tensor]) -> None: |
| 86 | + y_pred, y = output |
| 87 | + |
| 88 | + if y_pred.ndim < 2: |
| 89 | + raise ValueError(f"y_pred must be at least 2-dimensional (got shape: {y_pred.shape})") |
| 90 | + |
| 91 | + if y.ndim < 1: |
| 92 | + raise ValueError(f"y must be at least 1-dimensional (got shape: {y.shape})") |
| 93 | + |
| 94 | + nll = F.cross_entropy(y_pred, y, reduction="sum") |
| 95 | + self._sum_of_nll += nll.to(self._device, dtype=torch.double) |
| 96 | + self._num_tokens += y.numel() |
| 97 | + |
| 98 | + @sync_all_reduce("_sum_of_nll", "_num_tokens") |
| 99 | + def compute(self) -> float: |
| 100 | + if self._num_tokens == 0: |
| 101 | + raise NotComputableError("Perplexity must have at least one example before it can be computed.") |
| 102 | + |
| 103 | + return torch.exp(self._sum_of_nll / self._num_tokens).item() |
0 commit comments