|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from typing import TypeVar |
| 4 | + |
| 5 | +from torch import Tensor |
| 6 | + |
| 7 | +from torchjd.aggregation._mixins import Stateful |
| 8 | + |
| 9 | +from ._weighting_bases import Weighting |
| 10 | + |
| 11 | +_T = TypeVar("_T", contravariant=True, bound=Tensor) |
| 12 | + |
| 13 | + |
| 14 | +class CRMOGMWeighting(Weighting[_T], Stateful): |
| 15 | + r""" |
| 16 | + :class:`~torchjd.aggregation._mixins.Stateful` |
| 17 | + :class:`~torchjd.aggregation._weighting_bases.Weighting` that wraps another |
| 18 | + :class:`~torchjd.aggregation._weighting_bases.Weighting` and stabilises the weights it |
| 19 | + produces with an exponential moving average (EMA) across calls. This is the weight-smoothing |
| 20 | + modifier from `On the Convergence of Stochastic Multi-Objective Gradient Manipulation and |
| 21 | + Beyond <https://proceedings.neurips.cc/paper_files/paper/2022/file/f91bd64a3620aad8e70a27ad9cb3ca57-Paper-Conference.pdf>`_ |
| 22 | + (NeurIPS 2022). |
| 23 | +
|
| 24 | + Let :math:`\hat{\lambda}_k` be the weights returned by the wrapped weighting at step |
| 25 | + :math:`k`. The smoothed weights returned by ``CRMOGMWeighting`` are: |
| 26 | +
|
| 27 | + .. math:: |
| 28 | +
|
| 29 | + \lambda_k = \alpha \, \lambda_{k-1} + (1 - \alpha) \, \hat{\lambda}_k |
| 30 | +
|
| 31 | + where :math:`\lambda_0` is ``initial_weights`` if provided, otherwise |
| 32 | + :math:`\lambda_0 = \hat{\lambda}_1` (so that the first smoothed output equals |
| 33 | + :math:`\hat{\lambda}_1` regardless of :math:`\alpha`). |
| 34 | +
|
| 35 | + Creating the corresponding :class:`~torchjd.aggregation.Aggregator` from a wrapped weighting can |
| 36 | + be done by composing it with the appropriate aggregator subclass |
| 37 | + (:class:`~torchjd.aggregation.WeightedAggregator` or |
| 38 | + :class:`~torchjd.aggregation.GramianWeightedAggregator`) |
| 39 | +
|
| 40 | + The following example shows how to instantiate a Gramian-based weighted aggregator whose |
| 41 | + Gramian weighting is wrapped by CR-MOGM. |
| 42 | +
|
| 43 | + .. testcode:: python |
| 44 | +
|
| 45 | + from torchjd.aggregation import CRMOGMWeighting, GramianWeightedAggregator, UPGradWeighting |
| 46 | +
|
| 47 | + aggregator = GramianWeightedAggregator(CRMOGMWeighting(UPGradWeighting())) |
| 48 | +
|
| 49 | + The following example shows how to instantiate a Matrix-based weighted aggregator whose |
| 50 | + weighting is wrapped by CR-MOGM. |
| 51 | +
|
| 52 | + .. testcode:: python |
| 53 | +
|
| 54 | + from torchjd.aggregation import CRMOGMWeighting, MeanWeighting, WeightedAggregator |
| 55 | +
|
| 56 | + aggregator = WeightedAggregator(CRMOGMWeighting(MeanWeighting())) |
| 57 | +
|
| 58 | + Note that here, :class:`~torchjd.aggregation.MeanWeighting` is used just for the sake of the |
| 59 | + example: the exponential moving average of constant weights will always be equal to the weights |
| 60 | + themselves, so wrapping by ``CRMOGMWeighting`` will have no effect. |
| 61 | +
|
| 62 | + This weighting is stateful: it keeps :math:`\lambda_{k-1}` across calls. Use :meth:`reset` |
| 63 | + to restart the smoothing from the initial state. Note that calling :meth:`reset` will also |
| 64 | + reset the wrapped weighting if it is :class:`~torchjd.aggregation.Stateful`. |
| 65 | +
|
| 66 | + :param weighting: The wrapped weighting whose output is smoothed. |
| 67 | + :param alpha: EMA coefficient on the previous weights. ``alpha=0`` disables smoothing |
| 68 | + (``CRMOGMWeighting`` returns ``weighting``'s output verbatim) and ``alpha=1`` freezes |
| 69 | + the weights at their initial value. The default of ``0.9`` follows the usual EMA |
| 70 | + convention (analogous to Adam's :math:`\beta_1`). |
| 71 | + :param initial_weights: Optional tensor to use as :math:`\lambda_0`. If ``None`` (default), |
| 72 | + :math:`\lambda_0` is set to :math:`\hat{\lambda}_1` on the first forward call, making |
| 73 | + the first smoothed output equal to :math:`\hat{\lambda}_1`. |
| 74 | +
|
| 75 | + .. note:: |
| 76 | + ``alpha`` is a fixed ``float`` for simplicity. Corollary 1 of the paper recommends a |
| 77 | + schedule where :math:`\alpha_k` starts near 0 and increases toward 1 as the learning |
| 78 | + rate decays. Update ``alpha`` between forward calls via the setter. |
| 79 | +
|
| 80 | + The following example shows how to update alpha with the suggested scheme from the paper, |
| 81 | + when the aggregator is a Gramian-based weighted aggregator whose Gramian weighting is |
| 82 | + wrapped by CR-MOGM: |
| 83 | +
|
| 84 | + .. testcode:: python |
| 85 | +
|
| 86 | + from torchjd.aggregation import ( |
| 87 | + CRMOGMWeighting, |
| 88 | + GramianWeightedAggregator, |
| 89 | + UPGradWeighting, |
| 90 | + ) |
| 91 | +
|
| 92 | + aggregator = GramianWeightedAggregator(CRMOGMWeighting(UPGradWeighting())) |
| 93 | +
|
| 94 | + initial_lr = 0.1 |
| 95 | + current_lr = 0.05 # e.g. obtained from lr_scheduler.get_lr()[0] |
| 96 | +
|
| 97 | + cr_mogm = aggregator.gramian_weighting |
| 98 | + cr_mogm.alpha = 1 - current_lr / initial_lr |
| 99 | + """ |
| 100 | + |
| 101 | + def __init__( |
| 102 | + self, weighting: Weighting[_T], alpha: float = 0.9, initial_weights: Tensor | None = None |
| 103 | + ) -> None: |
| 104 | + super().__init__() |
| 105 | + self.weighting = weighting |
| 106 | + self.alpha = alpha |
| 107 | + self._initial_weights = initial_weights |
| 108 | + self._lambda: Tensor | None = None |
| 109 | + |
| 110 | + @property |
| 111 | + def alpha(self) -> float: |
| 112 | + return self._alpha |
| 113 | + |
| 114 | + @alpha.setter |
| 115 | + def alpha(self, value: float) -> None: |
| 116 | + if not (0.0 <= value <= 1.0): |
| 117 | + raise ValueError(f"Attribute `alpha` must be in [0, 1]. Found alpha={value!r}.") |
| 118 | + self._alpha = value |
| 119 | + |
| 120 | + def reset(self) -> None: |
| 121 | + r""" |
| 122 | + Clears the EMA state so the next forward restarts from the initial state. Also resets the |
| 123 | + wrapped weighting if it is :class:`~torchjd.aggregation._mixins.Stateful`. |
| 124 | + """ |
| 125 | + |
| 126 | + if isinstance(self.weighting, Stateful): |
| 127 | + self.weighting.reset() |
| 128 | + self._lambda = None |
| 129 | + |
| 130 | + def forward(self, stat: _T, /) -> Tensor: |
| 131 | + lambda_hat = self.weighting(stat) |
| 132 | + lambda_prev = self._ensure_state(lambda_hat) |
| 133 | + self._lambda = self._alpha * lambda_prev + (1.0 - self._alpha) * lambda_hat |
| 134 | + return self._lambda |
| 135 | + |
| 136 | + def _ensure_state(self, lambda_hat: Tensor) -> Tensor: |
| 137 | + m = lambda_hat.shape[0] |
| 138 | + if self._lambda is None: |
| 139 | + if self._initial_weights is not None: |
| 140 | + if self._initial_weights.shape != (m,): |
| 141 | + raise ValueError( |
| 142 | + f"`initial_weights` has shape {tuple(self._initial_weights.shape)}, " |
| 143 | + f"expected ({m},)." |
| 144 | + ) |
| 145 | + self._lambda = self._initial_weights.to( |
| 146 | + dtype=lambda_hat.dtype, device=lambda_hat.device |
| 147 | + ) |
| 148 | + else: |
| 149 | + self._lambda = lambda_hat |
| 150 | + elif self._lambda.shape[0] != m: |
| 151 | + raise ValueError( |
| 152 | + f"The number of objectives changed from {self._lambda.shape[0]} to {m}. Call " |
| 153 | + f"`reset()` before changing the number of objectives." |
| 154 | + ) |
| 155 | + return self._lambda |
0 commit comments