|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# Copyright (c) Meta Platforms, Inc. and affiliates. |
| 3 | +# All rights reserved. |
| 4 | +# |
| 5 | +# This source code is licensed under the BSD-style license found in the |
| 6 | +# LICENSE file in the root directory of this source tree. |
| 7 | + |
| 8 | +# pyre-strict |
| 9 | + |
| 10 | +from typing import Any, Dict, Optional, Type |
| 11 | + |
| 12 | +import torch |
| 13 | + |
| 14 | +from torchrec.metrics.metrics_namespace import MetricNamespace |
| 15 | +from torchrec.metrics.ne import get_ne_states, NEMetricComputation |
| 16 | +from torchrec.metrics.rec_metric import ( |
| 17 | + RecMetric, |
| 18 | + RecMetricComputation, |
| 19 | + RecMetricException, |
| 20 | +) |
| 21 | + |
| 22 | + |
| 23 | +class RecalibratedNEMetricComputation(NEMetricComputation): |
| 24 | + r""" |
| 25 | + This class implements the recalibration for NE that is required to correctly estimate eval NE if negative downsampling was used during training. |
| 26 | +
|
| 27 | + The constructor arguments are defined in RecMetricComputation. |
| 28 | + See the docstring of RecMetricComputation for more detail. |
| 29 | +
|
| 30 | + Args: |
| 31 | + include_logloss (bool): return vanilla logloss as one of metrics results, on top of NE. |
| 32 | + """ |
| 33 | + |
| 34 | + def __init__( |
| 35 | + self, |
| 36 | + *args: Any, |
| 37 | + include_logloss: bool = False, |
| 38 | + allow_missing_label_with_zero_weight: bool = False, |
| 39 | + recalibration_coefficient: float = 1.0, |
| 40 | + **kwargs: Any, |
| 41 | + ) -> None: |
| 42 | + self._recalibration_coefficient: float = recalibration_coefficient |
| 43 | + self._include_logloss: bool = include_logloss |
| 44 | + self._allow_missing_label_with_zero_weight: bool = ( |
| 45 | + allow_missing_label_with_zero_weight |
| 46 | + ) |
| 47 | + super().__init__(*args, **kwargs) |
| 48 | + self._add_state( |
| 49 | + "cross_entropy_sum", |
| 50 | + torch.zeros(self._n_tasks, dtype=torch.double), |
| 51 | + add_window_state=True, |
| 52 | + dist_reduce_fx="sum", |
| 53 | + persistent=True, |
| 54 | + ) |
| 55 | + self._add_state( |
| 56 | + "weighted_num_samples", |
| 57 | + torch.zeros(self._n_tasks, dtype=torch.double), |
| 58 | + add_window_state=True, |
| 59 | + dist_reduce_fx="sum", |
| 60 | + persistent=True, |
| 61 | + ) |
| 62 | + self._add_state( |
| 63 | + "pos_labels", |
| 64 | + torch.zeros(self._n_tasks, dtype=torch.double), |
| 65 | + add_window_state=True, |
| 66 | + dist_reduce_fx="sum", |
| 67 | + persistent=True, |
| 68 | + ) |
| 69 | + self._add_state( |
| 70 | + "neg_labels", |
| 71 | + torch.zeros(self._n_tasks, dtype=torch.double), |
| 72 | + add_window_state=True, |
| 73 | + dist_reduce_fx="sum", |
| 74 | + persistent=True, |
| 75 | + ) |
| 76 | + self.eta = 1e-12 |
| 77 | + |
| 78 | + def _recalibrate( |
| 79 | + self, |
| 80 | + predictions: torch.Tensor, |
| 81 | + calibration_coef: Optional[torch.Tensor], |
| 82 | + ) -> torch.Tensor: |
| 83 | + if calibration_coef is not None: |
| 84 | + predictions = predictions / ( |
| 85 | + predictions + (1.0 - predictions) / calibration_coef |
| 86 | + ) |
| 87 | + return predictions |
| 88 | + |
| 89 | + def update( |
| 90 | + self, |
| 91 | + *, |
| 92 | + predictions: Optional[torch.Tensor], |
| 93 | + labels: torch.Tensor, |
| 94 | + weights: Optional[torch.Tensor], |
| 95 | + **kwargs: Dict[str, Any], |
| 96 | + ) -> None: |
| 97 | + if predictions is None or weights is None: |
| 98 | + raise RecMetricException( |
| 99 | + "Inputs 'predictions' and 'weights' should not be None for RecalibratedNEMetricComputation update" |
| 100 | + ) |
| 101 | + |
| 102 | + predictions = self._recalibrate( |
| 103 | + predictions, self._recalibration_coefficient * torch.ones_like(predictions) |
| 104 | + ) |
| 105 | + states = get_ne_states(labels, predictions, weights, self.eta) |
| 106 | + num_samples = predictions.shape[-1] |
| 107 | + |
| 108 | + for state_name, state_value in states.items(): |
| 109 | + state = getattr(self, state_name) |
| 110 | + state += state_value |
| 111 | + self._aggregate_window_state(state_name, state_value, num_samples) |
| 112 | + |
| 113 | + |
| 114 | +class RecalibratedNEMetric(RecMetric): |
| 115 | + _namespace: MetricNamespace = MetricNamespace.RECALIBRATED_NE |
| 116 | + _computation_class: Type[RecMetricComputation] = RecalibratedNEMetricComputation |
0 commit comments