|
| 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 | +from typing import Any, cast, Dict, List, Optional, Type |
| 9 | + |
| 10 | +import torch |
| 11 | +from torchrec.metrics.calibration import compute_calibration, get_calibration_states |
| 12 | +from torchrec.metrics.metrics_namespace import MetricName, MetricNamespace, MetricPrefix |
| 13 | +from torchrec.metrics.rec_metric import ( |
| 14 | + MetricComputationReport, |
| 15 | + RecMetric, |
| 16 | + RecMetricComputation, |
| 17 | + RecMetricException, |
| 18 | +) |
| 19 | + |
| 20 | +CALIBRATION_NUM = "calibration_num" |
| 21 | +CALIBRATION_DENOM = "calibration_denom" |
| 22 | +NUM_EXAMPLES = "num_examples" |
| 23 | + |
| 24 | + |
| 25 | +class ServingCalibrationMetricComputation(RecMetricComputation): |
| 26 | + r""" |
| 27 | + This class implements the RecMetricComputation for Calibration, which is the |
| 28 | + ratio between the prediction and the labels (conversions). |
| 29 | +
|
| 30 | + The constructor arguments are defined in RecMetricComputation. |
| 31 | + See the docstring of RecMetricComputation for more detail. |
| 32 | + """ |
| 33 | + |
| 34 | + def __init__(self, *args: Any, **kwargs: Any) -> None: |
| 35 | + super().__init__(*args, **kwargs) |
| 36 | + self._add_state( |
| 37 | + CALIBRATION_NUM, |
| 38 | + torch.zeros(self._n_tasks, dtype=torch.double), |
| 39 | + add_window_state=True, |
| 40 | + dist_reduce_fx="sum", |
| 41 | + persistent=True, |
| 42 | + ) |
| 43 | + self._add_state( |
| 44 | + CALIBRATION_DENOM, |
| 45 | + torch.zeros(self._n_tasks, dtype=torch.double), |
| 46 | + add_window_state=True, |
| 47 | + dist_reduce_fx="sum", |
| 48 | + persistent=True, |
| 49 | + ) |
| 50 | + self._add_state( |
| 51 | + NUM_EXAMPLES, |
| 52 | + torch.zeros(self._n_tasks, dtype=torch.long), |
| 53 | + add_window_state=False, |
| 54 | + dist_reduce_fx="sum", |
| 55 | + persistent=True, |
| 56 | + ) |
| 57 | + |
| 58 | + def update( |
| 59 | + self, |
| 60 | + *, |
| 61 | + predictions: Optional[torch.Tensor], |
| 62 | + labels: torch.Tensor, |
| 63 | + weights: Optional[torch.Tensor], |
| 64 | + **kwargs: Dict[str, Any], |
| 65 | + ) -> None: |
| 66 | + if predictions is None or weights is None: |
| 67 | + raise RecMetricException( |
| 68 | + "Inputs 'predictions' and 'weights' should not be None for CalibrationMetricComputation update" |
| 69 | + ) |
| 70 | + num_samples = predictions.shape[-1] |
| 71 | + for state_name, state_value in get_calibration_states( |
| 72 | + labels, predictions, weights |
| 73 | + ).items(): |
| 74 | + state = getattr(self, state_name) |
| 75 | + state += state_value |
| 76 | + self._aggregate_window_state(state_name, state_value, num_samples) |
| 77 | + |
| 78 | + num_examples_delta = torch.count_nonzero(weights, dim=-1) |
| 79 | + state_num_examples = getattr(self, NUM_EXAMPLES) |
| 80 | + state_num_examples += num_examples_delta |
| 81 | + |
| 82 | + def _compute(self) -> List[MetricComputationReport]: |
| 83 | + return [ |
| 84 | + MetricComputationReport( |
| 85 | + name=MetricName.CALIBRATION, |
| 86 | + metric_prefix=MetricPrefix.LIFETIME, |
| 87 | + value=compute_calibration( |
| 88 | + cast(torch.Tensor, self.calibration_num), |
| 89 | + cast(torch.Tensor, self.calibration_denom), |
| 90 | + ), |
| 91 | + ), |
| 92 | + MetricComputationReport( |
| 93 | + name=MetricName.CALIBRATION, |
| 94 | + metric_prefix=MetricPrefix.WINDOW, |
| 95 | + value=compute_calibration( |
| 96 | + self.get_window_state(CALIBRATION_NUM), |
| 97 | + self.get_window_state(CALIBRATION_DENOM), |
| 98 | + ), |
| 99 | + ), |
| 100 | + MetricComputationReport( |
| 101 | + name=MetricName.TOTAL_EXAMPLES, |
| 102 | + metric_prefix=MetricPrefix.DEFAULT, |
| 103 | + value=cast(torch.Tensor, self.num_examples).detach(), |
| 104 | + ), |
| 105 | + ] |
| 106 | + |
| 107 | + |
| 108 | +class ServingCalibrationMetric(RecMetric): |
| 109 | + _namespace: MetricNamespace = MetricNamespace.SERVING_CALIBRATION |
| 110 | + _computation_class: Type[RecMetricComputation] = ServingCalibrationMetricComputation |
0 commit comments