|
| 1 | +# Partly adapted from https://github.com/uiuctml/ExcessMTL — MIT License, Copyright (c) 2024 UIUC TML Lab. |
| 2 | +# See NOTICES for the full license text. |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +from typing import cast |
| 6 | + |
| 7 | +import torch |
| 8 | +from torch import Tensor |
| 9 | + |
| 10 | +from torchjd._mixins import Stateful |
| 11 | +from torchjd.aggregation._mixins import _NonDifferentiable |
| 12 | +from torchjd.linalg import Matrix |
| 13 | + |
| 14 | +from ._weighting_bases import _MatrixWeighting |
| 15 | + |
| 16 | + |
| 17 | +class ExcessMTLWeighting(_MatrixWeighting, Stateful, _NonDifferentiable): |
| 18 | + r""" |
| 19 | + :class:`~torchjd.Stateful` |
| 20 | + :class:`~torchjd.aggregation.Weighting` [:class:`~torchjd.linalg.Matrix`] from `Robust |
| 21 | + Multi-Task Learning with Excess Risks |
| 22 | + <https://proceedings.mlr.press/v235/he24n.html>`_ (ICML 2024). |
| 23 | +
|
| 24 | + At each call, task weights are updated via an exponentiated gradient step (Equation 9) driven |
| 25 | + by per-task excess risk estimates. The excess risk for task :math:`i` is approximated via a |
| 26 | + second-order Taylor expansion (Equations 6-7): |
| 27 | +
|
| 28 | + :param robust_step_size: Step size :math:`\eta_\alpha` for the exponentiated weight update. |
| 29 | + Must be positive. |
| 30 | + :param n_warmup_steps: Number of forward calls during which weights stay uniform |
| 31 | + (:math:`[1/m, \ldots, 1/m]`) and gradient statistics are collected. The baseline excess |
| 32 | + risk is set to the average excess risk observed during warmup. When ``0`` (default), the |
| 33 | + first call's excess risk is used as the baseline and weights are updated immediately |
| 34 | + (matching the official implementation). |
| 35 | +
|
| 36 | + .. warning:: |
| 37 | + The state tensor :math:`S \in \mathbb{R}^{m \times n}` accumulates squared gradients |
| 38 | + across **all** calls, where :math:`n` is the total number of model parameters. For large |
| 39 | + models this can be a significant memory cost. Call :meth:`reset` between experiments. |
| 40 | +
|
| 41 | + .. note:: |
| 42 | + The weight update is adapted from the `official implementation |
| 43 | + <https://github.com/uiuctml/ExcessMTL>`_ and `LibMTL |
| 44 | + <https://github.com/median-research-group/LibMTL/blob/main/LibMTL/weighting/ExcessMTL.py>`_. |
| 45 | + The warmup strategy follows Appendix C.1 of the paper, which recommends collecting |
| 46 | + gradient statistics for several epochs before beginning weight updates; set |
| 47 | + ``n_warmup_steps`` accordingly (e.g. ``3 * len(dataloader)``). |
| 48 | +
|
| 49 | + .. admonition:: Example |
| 50 | +
|
| 51 | + .. testcode:: |
| 52 | +
|
| 53 | + import torch |
| 54 | + from torch.nn import Linear, MSELoss, ReLU, Sequential |
| 55 | + from torch.optim import SGD |
| 56 | +
|
| 57 | + from torchjd import autojac |
| 58 | + from torchjd.aggregation import ExcessMTLWeighting, WeightedAggregator |
| 59 | + from torchjd.autojac import jac_to_grad |
| 60 | +
|
| 61 | + inputs = torch.randn(8, 5) |
| 62 | + targets = torch.randn(8, 2) |
| 63 | +
|
| 64 | + model = Sequential(Linear(5, 4), ReLU(), Linear(4, 2)) |
| 65 | + optimizer = SGD(model.parameters()) |
| 66 | + criterion = MSELoss() |
| 67 | + aggregator = WeightedAggregator(ExcessMTLWeighting()) |
| 68 | +
|
| 69 | + outputs = model(inputs) |
| 70 | + losses = [criterion(outputs[:, i], targets[:, i]) for i in range(2)] |
| 71 | + autojac.backward(losses) |
| 72 | + jac_to_grad(model.parameters(), aggregator) |
| 73 | + optimizer.step() |
| 74 | + optimizer.zero_grad() |
| 75 | + """ |
| 76 | + |
| 77 | + def __init__( |
| 78 | + self, |
| 79 | + robust_step_size: float = 1.0, |
| 80 | + n_warmup_steps: int = 0, |
| 81 | + ) -> None: |
| 82 | + super().__init__() |
| 83 | + self.robust_step_size = robust_step_size |
| 84 | + self.n_warmup_steps = n_warmup_steps |
| 85 | + self.register_buffer("_weights", None) |
| 86 | + self.register_buffer("_grad_sum", None) |
| 87 | + self.register_buffer("_initial_w", None) |
| 88 | + self.register_buffer("_warmup_w_sum", None) |
| 89 | + self.register_buffer("_n_steps", torch.zeros((), dtype=torch.long)) |
| 90 | + self._state_key: tuple[int, int, torch.dtype, torch.device] | None = None |
| 91 | + |
| 92 | + @property |
| 93 | + def robust_step_size(self) -> float: |
| 94 | + return self._robust_step_size |
| 95 | + |
| 96 | + @robust_step_size.setter |
| 97 | + def robust_step_size(self, value: float) -> None: |
| 98 | + if value <= 0.0: |
| 99 | + raise ValueError( |
| 100 | + f"Attribute `robust_step_size` must be positive. Found robust_step_size={value!r}." |
| 101 | + ) |
| 102 | + self._robust_step_size = value |
| 103 | + |
| 104 | + @property |
| 105 | + def n_warmup_steps(self) -> int: |
| 106 | + return self._n_warmup_steps |
| 107 | + |
| 108 | + @n_warmup_steps.setter |
| 109 | + def n_warmup_steps(self, value: int) -> None: |
| 110 | + if value < 0: |
| 111 | + raise ValueError( |
| 112 | + f"Attribute `n_warmup_steps` must be non-negative. Found n_warmup_steps={value!r}." |
| 113 | + ) |
| 114 | + self._n_warmup_steps = value |
| 115 | + |
| 116 | + def reset(self) -> None: |
| 117 | + """Clears all state so the next forward starts from uniform weights and re-enters |
| 118 | + warmup.""" |
| 119 | + |
| 120 | + self._weights = None |
| 121 | + self._grad_sum = None |
| 122 | + self._initial_w = None |
| 123 | + self._warmup_w_sum = None |
| 124 | + self._n_steps.zero_() |
| 125 | + self._state_key = None |
| 126 | + |
| 127 | + def forward(self, matrix: Matrix, /) -> Tensor: |
| 128 | + self._ensure_state(matrix) |
| 129 | + |
| 130 | + # Accumulate squared gradients for AdaGrad-style diagonal Hessian (Equation 7) |
| 131 | + grad_sum = cast(Tensor, self._grad_sum) |
| 132 | + grad_sum = grad_sum + matrix.detach() ** 2 |
| 133 | + self._grad_sum = grad_sum |
| 134 | + |
| 135 | + # Excess risk proxy: Ê_i ≈ g_i^T H_i^{-1} g_i (Equation 6) |
| 136 | + h = torch.sqrt(grad_sum + 1e-7) |
| 137 | + w = (matrix.detach() ** 2 / h).sum(dim=1) # shape [m] |
| 138 | + |
| 139 | + n_steps = int(self._n_steps.item()) |
| 140 | + self._n_steps = self._n_steps + 1 |
| 141 | + |
| 142 | + # Warmup: collect excess risk stats but return uniform weights |
| 143 | + if n_steps < self._n_warmup_steps: |
| 144 | + warmup_w_sum = self._warmup_w_sum |
| 145 | + self._warmup_w_sum = w if warmup_w_sum is None else cast(Tensor, warmup_w_sum) + w |
| 146 | + return cast(Tensor, self._weights) |
| 147 | + |
| 148 | + # Set baseline on the first non-warmup call |
| 149 | + if self._initial_w is None: |
| 150 | + if self._n_warmup_steps > 0: |
| 151 | + # Average excess risk observed during warmup (Appendix C.1) |
| 152 | + self._initial_w = cast(Tensor, self._warmup_w_sum) / self._n_warmup_steps |
| 153 | + w = w / (cast(Tensor, self._initial_w) + 1e-7) |
| 154 | + else: |
| 155 | + # Official impl behaviour: first call's excess is the baseline; use w raw |
| 156 | + self._initial_w = w |
| 157 | + else: |
| 158 | + w = w / (cast(Tensor, self._initial_w) + 1e-7) |
| 159 | + |
| 160 | + # Exponentiated gradient weight update (Equation 9) |
| 161 | + weights = cast(Tensor, self._weights) |
| 162 | + weights = weights * torch.exp(w * self._robust_step_size) |
| 163 | + weights = weights / weights.sum() |
| 164 | + self._weights = weights |
| 165 | + return weights |
| 166 | + |
| 167 | + def _ensure_state(self, matrix: Matrix) -> None: |
| 168 | + key = (matrix.shape[0], matrix.shape[1], matrix.dtype, matrix.device) |
| 169 | + if self._state_key == key and self._grad_sum is not None: |
| 170 | + return |
| 171 | + m, n = matrix.shape |
| 172 | + self._grad_sum = matrix.new_zeros(m, n) |
| 173 | + self._weights = matrix.new_full((m,), 1.0 / m) |
| 174 | + self._initial_w = None |
| 175 | + self._warmup_w_sum = None |
| 176 | + self._n_steps.zero_() |
| 177 | + self._state_key = key |
| 178 | + |
| 179 | + def __repr__(self) -> str: |
| 180 | + return ( |
| 181 | + f"{self.__class__.__name__}(" |
| 182 | + f"robust_step_size={self.robust_step_size!r}, " |
| 183 | + f"n_warmup_steps={self.n_warmup_steps!r})" |
| 184 | + ) |
0 commit comments