|
| 1 | +# Partly adapted from https://github.com/OptMN-Lab/fairgrad/blob/main/methods/weight_methods.py#L811-L825 — MIT License, Copyright (c) 2024 OptMN-Lab. |
| 2 | +# See NOTICES for the full license text. |
| 3 | + |
| 4 | +from __future__ import annotations |
| 5 | + |
| 6 | +import contextlib |
| 7 | + |
| 8 | +import torch |
| 9 | +from torch import Tensor |
| 10 | + |
| 11 | +from torchjd._mixins import _WithOptionalDeps |
| 12 | +from torchjd.linalg import PSDMatrix |
| 13 | + |
| 14 | +from ._aggregator_bases import GramianWeightedAggregator |
| 15 | +from ._mixins import _NonDifferentiable |
| 16 | +from ._weighting_bases import _GramianWeighting |
| 17 | + |
| 18 | +with contextlib.suppress(ImportError): |
| 19 | + import numpy as np |
| 20 | + from scipy.optimize import least_squares |
| 21 | + |
| 22 | + |
| 23 | +# Non-differentiable: the scipy solver operates on numpy arrays, breaking the autograd graph. |
| 24 | +class FairGradWeighting(_WithOptionalDeps, _NonDifferentiable, _GramianWeighting): |
| 25 | + r""" |
| 26 | + :class:`~torchjd.aggregation.Weighting` [:class:`~torchjd.linalg.PSDMatrix`] giving the |
| 27 | + weights of :class:`~torchjd.aggregation.FairGrad`, as defined in Equation 4 of `Fair Resource |
| 28 | + Allocation in Multi-Task Learning <https://arxiv.org/pdf/2402.15638>`_. |
| 29 | +
|
| 30 | + :param alpha: The parameter controlling the type of fairness in the alpha-fairness |
| 31 | + formulation. |
| 32 | + :param max_iters: The maximum number of iterations of the optimization loop. If set to None, |
| 33 | + the default value of ``scipy.optimize.least_squares`` (``100 * m``) will be used. |
| 34 | +
|
| 35 | + .. note:: |
| 36 | + This implementation was adapted from the `official implementation |
| 37 | + <https://github.com/OptMN-Lab/fairgrad/blob/main/methods/weight_methods.py#L811-L825>`_. |
| 38 | +
|
| 39 | + .. note:: |
| 40 | + This aggregator requires optional dependencies. When they are not installed, instantiating |
| 41 | + it raises an :class:`ImportError` with installation instructions. |
| 42 | + To install them, use ``pip install "torchjd[fairgrad]"``. |
| 43 | + """ |
| 44 | + |
| 45 | + _REQUIRED_DEPS = ["numpy", "scipy"] |
| 46 | + _INSTALL_HINT = 'Install it with: pip install "torchjd[fairgrad]"' |
| 47 | + |
| 48 | + def __init__(self, alpha: float, max_iters: int | None = None) -> None: |
| 49 | + super().__init__() |
| 50 | + self.alpha = alpha |
| 51 | + self.max_iters = max_iters |
| 52 | + |
| 53 | + def forward(self, gramian: PSDMatrix, /) -> Tensor: |
| 54 | + m = gramian.shape[0] |
| 55 | + uniform = np.ones(m) / m |
| 56 | + |
| 57 | + if self.alpha == 0: |
| 58 | + # When alpha=0, the alpha-fairness formulation reduces to linear scalarization with |
| 59 | + # uniform weights (see Section 3 of https://arxiv.org/pdf/2402.15638). |
| 60 | + weight_array = uniform |
| 61 | + else: |
| 62 | + gramian_array = gramian.detach().cpu().numpy() |
| 63 | + |
| 64 | + def objective(x: np.ndarray) -> np.ndarray: |
| 65 | + return np.dot(gramian_array, x) - np.power(x, -1.0 / self.alpha) |
| 66 | + |
| 67 | + res = least_squares(objective, uniform, bounds=(0, np.inf), max_nfev=self.max_iters) |
| 68 | + weight_array = res.x |
| 69 | + |
| 70 | + return torch.tensor(weight_array).to(device=gramian.device, dtype=gramian.dtype) |
| 71 | + |
| 72 | + @property |
| 73 | + def alpha(self) -> float: |
| 74 | + return self._alpha |
| 75 | + |
| 76 | + @alpha.setter |
| 77 | + def alpha(self, value: float) -> None: |
| 78 | + self._alpha = value |
| 79 | + |
| 80 | + |
| 81 | +class FairGrad(_NonDifferentiable, GramianWeightedAggregator): |
| 82 | + r""" |
| 83 | + :class:`~torchjd.aggregation.GramianWeightedAggregator` using the step decision of Algorithm 1 |
| 84 | + of `Fair Resource Allocation in Multi-Task Learning |
| 85 | + <https://arxiv.org/pdf/2402.15638.pdf>`_. |
| 86 | +
|
| 87 | + :param alpha: The parameter controlling the type of fairness in the alpha-fairness |
| 88 | + formulation. |
| 89 | + :param max_iters: The maximum number of iterations of the optimization loop. If set to None, |
| 90 | + the default value of ``scipy.optimize.least_squares`` (``100 * m``) will be used. |
| 91 | +
|
| 92 | + .. note:: |
| 93 | + This aggregator requires optional dependencies. When they are not installed, instantiating |
| 94 | + it raises an :class:`ImportError` with installation instructions. |
| 95 | + To install them, use ``pip install "torchjd[fairgrad]"``. |
| 96 | + """ |
| 97 | + |
| 98 | + gramian_weighting: FairGradWeighting |
| 99 | + |
| 100 | + def __init__(self, alpha: float, max_iters: int | None = None) -> None: |
| 101 | + super().__init__(FairGradWeighting(alpha=alpha, max_iters=max_iters)) |
| 102 | + |
| 103 | + @property |
| 104 | + def alpha(self) -> float: |
| 105 | + return self.gramian_weighting.alpha |
| 106 | + |
| 107 | + @alpha.setter |
| 108 | + def alpha(self, value: float) -> None: |
| 109 | + self.gramian_weighting.alpha = value |
| 110 | + |
| 111 | + @property |
| 112 | + def max_iters(self) -> int | None: |
| 113 | + return self.gramian_weighting.max_iters |
| 114 | + |
| 115 | + @max_iters.setter |
| 116 | + def max_iters(self, value: int | None) -> None: |
| 117 | + self.gramian_weighting.max_iters = value |
| 118 | + |
| 119 | + def __repr__(self) -> str: |
| 120 | + return f"{self.__class__.__name__}(alpha={self.alpha}, max_iters={self.max_iters})" |
| 121 | + |
| 122 | + def __str__(self) -> str: |
| 123 | + return f"{self.alpha}-FairGrad" |
0 commit comments