|
| 1 | +# Partly adapted from https://github.com/heshandevaka/Trade-Off-MOL — MIT License, Copyright (c) 2023 Heshan Fernando. |
| 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.aggregation._mixins import Stateful, _NonDifferentiable |
| 11 | +from torchjd.linalg import Matrix |
| 12 | + |
| 13 | +from ._weighting_bases import _MatrixWeighting |
| 14 | + |
| 15 | + |
| 16 | +class MoDoWeighting(_MatrixWeighting, Stateful, _NonDifferentiable): |
| 17 | + r""" |
| 18 | + :class:`~torchjd.aggregation._mixins.Stateful` |
| 19 | + :class:`~torchjd.aggregation.Weighting` [:class:`~torchjd.linalg.Matrix`] from `Three-Way |
| 20 | + Trade-Off in Multi-Objective Learning: Optimization, Generalization and Conflict-Avoidance |
| 21 | + <https://www.jmlr.org/papers/volume25/23-1287/23-1287.pdf>`_ (JMLR 2024). |
| 22 | +
|
| 23 | + .. warning:: |
| 24 | + The input matrix must be :math:`G = J_1 J_2^\top`, computed from two **independent** |
| 25 | + mini-batches via :func:`torchjd.autojac.jac`. Using a single-batch Gramian |
| 26 | + (:math:`J_1 J_1^\top`) breaks the convergence guarantee. See the usage examples below. |
| 27 | +
|
| 28 | + :param gamma: Learning rate of the task-weight update. Must be positive. |
| 29 | + :param rho: Non-negative :math:`\ell_2` regularisation coefficient. |
| 30 | +
|
| 31 | + .. note:: |
| 32 | + The Euclidean projection onto the simplex used in the :math:`\lambda` update is adapted from |
| 33 | + the `official implementation <https://github.com/heshandevaka/Trade-Off-MOL/blob/main/LibMTL/LibMTL/weighting/MoDo.py>`_. |
| 34 | +
|
| 35 | + .. admonition:: Example (two batches per step) |
| 36 | +
|
| 37 | + The following example reproduces basic MoDo using two independent mini-batches per step. |
| 38 | + This matches MoDo as described in the paper, and the behavior of the official |
| 39 | + implementation when ``three_grads`` is ``False``. |
| 40 | +
|
| 41 | + .. testcode:: |
| 42 | +
|
| 43 | + import torch |
| 44 | + from torch.nn import Linear, MSELoss, ReLU, Sequential |
| 45 | + from torch.optim import SGD |
| 46 | +
|
| 47 | + from torchjd.aggregation import MoDoWeighting |
| 48 | + from torchjd.autojac import jac |
| 49 | +
|
| 50 | + # Generate data (8 batches of 16 examples of dim 5) for the sake of the example. |
| 51 | + inputs = torch.randn(8, 16, 5) |
| 52 | + targets = torch.randn(8, 16) |
| 53 | +
|
| 54 | + model = Sequential(Linear(5, 4), ReLU(), Linear(4, 1)) |
| 55 | + optimizer = SGD(model.parameters()) |
| 56 | + criterion = MSELoss(reduction="none") |
| 57 | + weighting = MoDoWeighting(gamma=0.1, rho=0.0) |
| 58 | + params = list(model.parameters()) |
| 59 | +
|
| 60 | + # Consume two consecutive (independent) batches per step. |
| 61 | + for i in range(len(inputs) // 2): |
| 62 | + input_1, input_2 = inputs[2 * i], inputs[2 * i + 1] |
| 63 | + target_1, target_2 = targets[2 * i], targets[2 * i + 1] |
| 64 | +
|
| 65 | + # retain_graph=True so both graphs survive for the backward step below. |
| 66 | + losses_1 = criterion(model(input_1).squeeze(dim=1), target_1) |
| 67 | + jacs_1 = jac(losses_1, params, retain_graph=True) |
| 68 | + J_1 = torch.cat([j.flatten(1) for j in jacs_1], dim=1) |
| 69 | +
|
| 70 | + losses_2 = criterion(model(input_2).squeeze(dim=1), target_2) |
| 71 | + jacs_2 = jac(losses_2, params, retain_graph=True) |
| 72 | + J_2 = torch.cat([j.flatten(1) for j in jacs_2], dim=1) |
| 73 | +
|
| 74 | + G = J_1 @ J_2.T |
| 75 | + weights = weighting(G) |
| 76 | +
|
| 77 | + # Equation 2.9b: the parameter update uses the mean of both batches' losses. |
| 78 | + losses = (losses_1 + losses_2) / 2.0 |
| 79 | + losses.backward(weights) |
| 80 | + optimizer.step() |
| 81 | + optimizer.zero_grad() |
| 82 | +
|
| 83 | + .. admonition:: Example (three batches per step) |
| 84 | +
|
| 85 | + The following example reproduces basic MoDo using three independent mini-batches per step, |
| 86 | + keeping the :math:`\lambda` update and the parameter update on separate draws. This matches |
| 87 | + the behavior of LibMTL and of the official implementation when ``three_grads`` is ``True``. |
| 88 | +
|
| 89 | + .. testcode:: |
| 90 | +
|
| 91 | + import torch |
| 92 | + from torch.nn import Linear, MSELoss, ReLU, Sequential |
| 93 | + from torch.optim import SGD |
| 94 | +
|
| 95 | + from torchjd.aggregation import MoDoWeighting |
| 96 | + from torchjd.autojac import jac |
| 97 | +
|
| 98 | + # Generate data (9 batches of 16 examples of dim 5) for the sake of the example. |
| 99 | + inputs = torch.randn(9, 16, 5) |
| 100 | + targets = torch.randn(9, 16) |
| 101 | +
|
| 102 | + model = Sequential(Linear(5, 4), ReLU(), Linear(4, 1)) |
| 103 | + optimizer = SGD(model.parameters()) |
| 104 | + criterion = MSELoss(reduction="none") |
| 105 | + weighting = MoDoWeighting(gamma=0.1, rho=0.0) |
| 106 | + params = list(model.parameters()) |
| 107 | +
|
| 108 | + # Consume three consecutive (independent) batches per step. |
| 109 | + for i in range(len(inputs) // 3): |
| 110 | + input_1, input_2, input_3 = inputs[3 * i], inputs[3 * i + 1], inputs[3 * i + 2] |
| 111 | + target_1, target_2, target_3 = targets[3 * i], targets[3 * i + 1], targets[3 * i + 2] |
| 112 | +
|
| 113 | + losses_1 = criterion(model(input_1).squeeze(dim=1), target_1) |
| 114 | + jacs_1 = jac(losses_1, params) |
| 115 | + J_1 = torch.cat([j.flatten(1) for j in jacs_1], dim=1) |
| 116 | +
|
| 117 | + losses_2 = criterion(model(input_2).squeeze(dim=1), target_2) |
| 118 | + jacs_2 = jac(losses_2, params) |
| 119 | + J_2 = torch.cat([j.flatten(1) for j in jacs_2], dim=1) |
| 120 | +
|
| 121 | + G = J_1 @ J_2.T |
| 122 | + weights = weighting(G) |
| 123 | +
|
| 124 | + losses_3 = criterion(model(input_3).squeeze(dim=1), target_3) |
| 125 | + losses_3.backward(weights) |
| 126 | + optimizer.step() |
| 127 | + optimizer.zero_grad() |
| 128 | + """ |
| 129 | + |
| 130 | + def __init__(self, gamma: float = 0.1, rho: float = 0.1) -> None: |
| 131 | + super().__init__() |
| 132 | + self.gamma = gamma |
| 133 | + self.rho = rho |
| 134 | + self._lambda: Tensor | None = None |
| 135 | + self._state_key: tuple[int, torch.dtype, torch.device] | None = None |
| 136 | + |
| 137 | + @property |
| 138 | + def gamma(self) -> float: |
| 139 | + return self._gamma |
| 140 | + |
| 141 | + @gamma.setter |
| 142 | + def gamma(self, value: float) -> None: |
| 143 | + if value <= 0.0: |
| 144 | + raise ValueError(f"Attribute `gamma` must be positive. Found gamma={value!r}.") |
| 145 | + self._gamma = value |
| 146 | + |
| 147 | + @property |
| 148 | + def rho(self) -> float: |
| 149 | + return self._rho |
| 150 | + |
| 151 | + @rho.setter |
| 152 | + def rho(self, value: float) -> None: |
| 153 | + if value < 0.0: |
| 154 | + raise ValueError(f"Attribute `rho` must be non-negative. Found rho={value!r}.") |
| 155 | + self._rho = value |
| 156 | + |
| 157 | + def reset(self) -> None: |
| 158 | + """Clears the stored task weights so the next forward starts from uniform.""" |
| 159 | + |
| 160 | + self._lambda = None |
| 161 | + self._state_key = None |
| 162 | + |
| 163 | + def forward(self, matrix: Matrix, /) -> Tensor: |
| 164 | + self._ensure_state(matrix) |
| 165 | + lambd = cast(Tensor, self._lambda) |
| 166 | + |
| 167 | + grad = matrix @ lambd + self._rho * lambd |
| 168 | + lambd = self._projection2simplex(lambd - self._gamma * grad) |
| 169 | + |
| 170 | + self._lambda = lambd |
| 171 | + return lambd |
| 172 | + |
| 173 | + @staticmethod |
| 174 | + def _projection2simplex(y: Tensor) -> Tensor: |
| 175 | + """Euclidean projection of ``y`` onto the probability simplex.""" |
| 176 | + |
| 177 | + m = len(y) |
| 178 | + sorted_y = torch.sort(y, descending=True)[0] |
| 179 | + tmpsum = y.new_zeros(()) |
| 180 | + tmax_f = (torch.sum(y) - 1.0) / m |
| 181 | + for i in range(m - 1): |
| 182 | + tmpsum = tmpsum + sorted_y[i] |
| 183 | + tmax = (tmpsum - 1.0) / (i + 1.0) |
| 184 | + if tmax > sorted_y[i + 1]: |
| 185 | + tmax_f = tmax |
| 186 | + break |
| 187 | + return torch.max(y - tmax_f, y.new_zeros(m)) |
| 188 | + |
| 189 | + def _ensure_state(self, matrix: Matrix) -> None: |
| 190 | + key = (matrix.shape[0], matrix.dtype, matrix.device) |
| 191 | + if self._state_key == key and self._lambda is not None: |
| 192 | + return |
| 193 | + self._lambda = matrix.new_full((matrix.shape[0],), 1.0 / matrix.shape[0]) |
| 194 | + self._state_key = key |
| 195 | + |
| 196 | + def __repr__(self) -> str: |
| 197 | + return f"{self.__class__.__name__}(gamma={self.gamma!r}, rho={self.rho!r})" |
0 commit comments