|
| 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 | +import copy |
| 11 | +from typing import Any, cast, Dict, Optional |
| 12 | + |
| 13 | +from torch import nn |
| 14 | + |
| 15 | +from torchrec.metrics.rec_metric import ( |
| 16 | + RecComputeMode, |
| 17 | + RecMetric, |
| 18 | + RecMetricComputation, |
| 19 | + RecMetricList, |
| 20 | +) |
| 21 | +from torchrec.metrics.throughput import ThroughputMetric |
| 22 | + |
| 23 | + |
| 24 | +class MetricStateSnapshot: |
| 25 | + """ |
| 26 | + Encapsulates both rec metrics reduced states and throughput metric snapshots |
| 27 | + for thread-safe CPU offloaded metric computation (updates and computes). |
| 28 | + """ |
| 29 | + |
| 30 | + def __init__( |
| 31 | + self, |
| 32 | + metric_states: Dict[str, Any], |
| 33 | + throughput_metric: Optional[ThroughputMetric], |
| 34 | + ) -> None: |
| 35 | + """ |
| 36 | + Args: |
| 37 | + metric_states (Dict[str, Any]): Reduced states from rec metrics |
| 38 | + throughput_metric (Optional[ThroughputMetric]): Deep copy of throughput metric |
| 39 | + """ |
| 40 | + self.metric_states = metric_states |
| 41 | + self.throughput_metric = throughput_metric |
| 42 | + |
| 43 | + @classmethod |
| 44 | + def from_metrics( |
| 45 | + cls, |
| 46 | + rec_metrics: RecMetricList, |
| 47 | + throughput_metric: Optional[ThroughputMetric] = None, |
| 48 | + ) -> "MetricStateSnapshot": |
| 49 | + """ |
| 50 | + Generate a MetricStateSnapshot before performing an all gather. This provides a consistent |
| 51 | + view of the local metric states without accessing the original references. |
| 52 | +
|
| 53 | + Apply reductions BEFORE queuing to reduce memory footprint. For instance, AUC holds a list of |
| 54 | + tensors which can be reduced to a list of a single tensor. Only reduce lists for |
| 55 | + fused mode compatibility. |
| 56 | + """ |
| 57 | + reduced_states: Dict[str, Any] = {} |
| 58 | + |
| 59 | + for metric in rec_metrics.rec_metrics: |
| 60 | + metric = cast(RecMetric, metric) |
| 61 | + compute_mode = metric._compute_mode |
| 62 | + if ( |
| 63 | + compute_mode == RecComputeMode.FUSED_TASKS_COMPUTATION |
| 64 | + or compute_mode == RecComputeMode.FUSED_TASKS_AND_STATES_COMPUTATION |
| 65 | + ): |
| 66 | + computation = metric._metrics_computations[0] |
| 67 | + _load_into_reduced_states( |
| 68 | + compute_mode.name, computation, reduced_states |
| 69 | + ) |
| 70 | + else: |
| 71 | + for task, computation in zip( |
| 72 | + metric._tasks, metric._metrics_computations |
| 73 | + ): |
| 74 | + _load_into_reduced_states(task.name, computation, reduced_states) |
| 75 | + |
| 76 | + # Snapshot throughput metric |
| 77 | + throughput_snapshot = None |
| 78 | + if throughput_metric: |
| 79 | + throughput_snapshot = copy.deepcopy(throughput_metric) |
| 80 | + |
| 81 | + return cls( |
| 82 | + metric_states=reduced_states, |
| 83 | + throughput_metric=throughput_snapshot, |
| 84 | + ) |
| 85 | + |
| 86 | + |
| 87 | +def _load_into_reduced_states( |
| 88 | + prefix: str, |
| 89 | + computation: nn.Module, |
| 90 | + reduced_states: Dict[str, Any], |
| 91 | +) -> None: |
| 92 | + """ |
| 93 | + Load the reduced states into the reduced_states dict. |
| 94 | +
|
| 95 | + Args: |
| 96 | + prefix (str): prefix for the metric computation |
| 97 | + computation (nn.Module): metric computation |
| 98 | + reduced_states (Dict[str, Any]): reduced states dict to load into |
| 99 | + """ |
| 100 | + computation = cast(RecMetricComputation, computation) |
| 101 | + computation_name = f"{prefix}_{computation.__class__.__name__}" |
| 102 | + |
| 103 | + for attr_name in computation._reductions: |
| 104 | + cache_key = f"{computation_name}_{attr_name}" |
| 105 | + original_value = getattr(computation, attr_name) |
| 106 | + reduction_fn = computation._reductions[attr_name] |
| 107 | + if callable(reduction_fn) and isinstance(original_value, list): |
| 108 | + reduced_value = reduction_fn(original_value) |
| 109 | + else: |
| 110 | + reduced_value = original_value |
| 111 | + |
| 112 | + reduced_states[cache_key] = reduced_value |
0 commit comments