|
| 1 | +from abc import ABC, abstractmethod |
| 2 | +from typing import Any, Callable, Optional |
| 3 | + |
| 4 | +import torch |
| 5 | + |
| 6 | +from pytorch_lightning.metrics import Metric |
| 7 | +from pytorch_lightning.metrics.utils import get_group_indexes |
| 8 | + |
| 9 | +#: get_group_indexes is used to group predictions belonging to the same query |
| 10 | + |
| 11 | +IGNORE_IDX = -100 |
| 12 | + |
| 13 | + |
| 14 | +class RetrievalMetric(Metric, ABC): |
| 15 | + r""" |
| 16 | + Works with binary data. Accepts integer or float predictions from a model output. |
| 17 | +
|
| 18 | + Forward accepts |
| 19 | + - ``indexes`` (long tensor): ``(N, ...)`` |
| 20 | + - ``preds`` (float or int tensor): ``(N, ...)`` |
| 21 | + - ``target`` (long or bool tensor): ``(N, ...)`` |
| 22 | +
|
| 23 | + `indexes`, `preds` and `target` must have the same dimension and will be flatten |
| 24 | + to single dimension once provided. |
| 25 | +
|
| 26 | + `indexes` indicate to which query a prediction belongs. |
| 27 | + Predictions will be first grouped by indexes. Then the |
| 28 | + real metric, defined by overriding the `_metric` method, |
| 29 | + will be computed as the mean of the scores over each query. |
| 30 | +
|
| 31 | + Args: |
| 32 | + query_without_relevant_docs: |
| 33 | + Specify what to do with queries that do not have at least a positive target. Choose from: |
| 34 | +
|
| 35 | + - ``'skip'``: skip those queries (default); if all queries are skipped, ``0.0`` is returned |
| 36 | + - ``'error'``: raise a ``ValueError`` |
| 37 | + - ``'pos'``: score on those queries is counted as ``1.0`` |
| 38 | + - ``'neg'``: score on those queries is counted as ``0.0`` |
| 39 | + exclude: |
| 40 | + Do not take into account predictions where the target is equal to this value. default `-100` |
| 41 | + compute_on_step: |
| 42 | + Forward only calls ``update()`` and return None if this is set to False. default: True |
| 43 | + dist_sync_on_step: |
| 44 | + Synchronize metric state across processes at each ``forward()`` |
| 45 | + before returning the value at the step. default: False |
| 46 | + process_group: |
| 47 | + Specify the process group on which synchronization is called. default: None (which selects |
| 48 | + the entire world) |
| 49 | + dist_sync_fn: |
| 50 | + Callback that performs the allgather operation on the metric state. When `None`, DDP |
| 51 | + will be used to perform the allgather. default: None |
| 52 | +
|
| 53 | + """ |
| 54 | + |
| 55 | + def __init__( |
| 56 | + self, |
| 57 | + query_without_relevant_docs: str = 'skip', |
| 58 | + exclude: int = IGNORE_IDX, |
| 59 | + compute_on_step: bool = True, |
| 60 | + dist_sync_on_step: bool = False, |
| 61 | + process_group: Optional[Any] = None, |
| 62 | + dist_sync_fn: Callable = None |
| 63 | + ): |
| 64 | + super().__init__( |
| 65 | + compute_on_step=compute_on_step, |
| 66 | + dist_sync_on_step=dist_sync_on_step, |
| 67 | + process_group=process_group, |
| 68 | + dist_sync_fn=dist_sync_fn |
| 69 | + ) |
| 70 | + |
| 71 | + query_without_relevant_docs_options = ('error', 'skip', 'pos', 'neg') |
| 72 | + if query_without_relevant_docs not in query_without_relevant_docs_options: |
| 73 | + raise ValueError( |
| 74 | + f"`query_without_relevant_docs` received a wrong value {query_without_relevant_docs}. " |
| 75 | + f"Allowed values are {query_without_relevant_docs_options}" |
| 76 | + ) |
| 77 | + |
| 78 | + self.query_without_relevant_docs = query_without_relevant_docs |
| 79 | + self.exclude = exclude |
| 80 | + |
| 81 | + self.add_state("idx", default=[], dist_reduce_fx=None) |
| 82 | + self.add_state("preds", default=[], dist_reduce_fx=None) |
| 83 | + self.add_state("target", default=[], dist_reduce_fx=None) |
| 84 | + |
| 85 | + def update(self, idx: torch.Tensor, preds: torch.Tensor, target: torch.Tensor) -> None: |
| 86 | + if not (idx.shape == target.shape == preds.shape): |
| 87 | + raise ValueError("`idx`, `preds` and `target` must be of the same shape") |
| 88 | + |
| 89 | + idx = idx.to(dtype=torch.int64).flatten() |
| 90 | + preds = preds.to(dtype=torch.float32).flatten() |
| 91 | + target = target.to(dtype=torch.int64).flatten() |
| 92 | + |
| 93 | + self.idx.append(idx) |
| 94 | + self.preds.append(preds) |
| 95 | + self.target.append(target) |
| 96 | + |
| 97 | + def compute(self) -> torch.Tensor: |
| 98 | + r""" |
| 99 | + First concat state `idx`, `preds` and `target` since they were stored as lists. After that, |
| 100 | + compute list of groups that will help in keeping together predictions about the same query. |
| 101 | + Finally, for each group compute the `_metric` if the number of positive targets is at least |
| 102 | + 1, otherwise behave as specified by `self.query_without_relevant_docs`. |
| 103 | + """ |
| 104 | + |
| 105 | + idx = torch.cat(self.idx, dim=0) |
| 106 | + preds = torch.cat(self.preds, dim=0) |
| 107 | + target = torch.cat(self.target, dim=0) |
| 108 | + |
| 109 | + res = [] |
| 110 | + kwargs = {'device': idx.device, 'dtype': torch.float32} |
| 111 | + |
| 112 | + groups = get_group_indexes(idx) |
| 113 | + for group in groups: |
| 114 | + |
| 115 | + mini_preds = preds[group] |
| 116 | + mini_target = target[group] |
| 117 | + |
| 118 | + if not mini_target.sum(): |
| 119 | + if self.query_without_relevant_docs == 'error': |
| 120 | + raise ValueError( |
| 121 | + f"`{self.__class__.__name__}.compute()` was provided with " |
| 122 | + f"a query without positive targets, indexes: {group}" |
| 123 | + ) |
| 124 | + if self.query_without_relevant_docs == 'pos': |
| 125 | + res.append(torch.tensor(1.0, **kwargs)) |
| 126 | + elif self.query_without_relevant_docs == 'neg': |
| 127 | + res.append(torch.tensor(0.0, **kwargs)) |
| 128 | + else: |
| 129 | + res.append(self._metric(mini_preds, mini_target)) |
| 130 | + |
| 131 | + if len(res) > 0: |
| 132 | + return torch.stack(res).mean() |
| 133 | + return torch.tensor(0.0, **kwargs) |
| 134 | + |
| 135 | + @abstractmethod |
| 136 | + def _metric(self, preds: torch.Tensor, target: torch.Tensor) -> torch.Tensor: |
| 137 | + r""" |
| 138 | + Compute a metric over a predictions and target of a single group. |
| 139 | + This method should be overridden by subclasses. |
| 140 | + """ |
0 commit comments