Skip to content

Commit 478f847

Browse files
authored
Merge branch 'main' into dependabot/pre_commit/https-/github.com/astral-sh/ruff-pre-commit-0.15.15
2 parents c7f8d48 + f095b0f commit 478f847

12 files changed

Lines changed: 606 additions & 1 deletion

File tree

‎CHANGELOG.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,10 @@ changelog does not include internal changes that do not affect the user.
1010

1111
### Added
1212

13+
- Added `STCH` from [Smooth Tchebycheff Scalarization for Multi-Objective
14+
Optimization](https://openreview.net/pdf?id=m4dO5L6eCp), a `Scalarizer` that combines the input
15+
tensor of values into a smooth approximation of their (weighted, shifted) maximum.
16+
- Added `MoDoWeighting` from [Three-Way Trade-Off in Multi-Objective Learning: Optimization, Generalization and Conflict-Avoidance](https://www.jmlr.org/papers/volume25/23-1287/23-1287.pdf) (JMLR 2024). It is a stateful `Weighting` that maintains task weights across calls via a simplex-projected gradient step on a cross-batch matrix `G = J_1 @ J_2.T`, computed from two independent mini-batches using `autojac.jac`.
1317
- Added `GeometricMean` (also known as GLS) studied in [MultiNet++: Multi-Stream Feature
1418
Aggregation and Geometric Loss Strategy for Multi-Task
1519
Learning](https://openaccess.thecvf.com/content_CVPRW_2019/papers/WAD/Chennupati_MultiNet_Multi-Stream_Feature_Aggregation_and_Geometric_Loss_Strategy_for_Multi-Task_CVPRW_2019_paper.pdf),

‎NOTICES‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,3 +112,31 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
112112
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
113113
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
114114
SOFTWARE.
115+
116+
-------------------------------------------------------------------------------
117+
118+
Project: MoDo
119+
Source: https://github.com/heshandevaka/Trade-Off-MOL/blob/main/LibMTL/LibMTL/weighting/MoDo.py
120+
Used in: src/torchjd/aggregation/_modo.py
121+
122+
MIT License
123+
124+
Copyright (c) 2023 Heshan Fernando
125+
126+
Permission is hereby granted, free of charge, to any person obtaining a copy
127+
of this software and associated documentation files (the "Software"), to deal
128+
in the Software without restriction, including without limitation the rights
129+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
130+
copies of the Software, and to permit persons to whom the Software is
131+
furnished to do so, subject to the following conditions:
132+
133+
The above copyright notice and this permission notice shall be included in all
134+
copies or substantial portions of the Software.
135+
136+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
137+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
138+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
139+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
140+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
141+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
142+
SOFTWARE.

‎docs/source/docs/aggregation/index.rst‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ Abstract base classes
4141
krum.rst
4242
mean.rst
4343
mgda.rst
44+
modo.rst
4445
nash_mtl.rst
4546
pcgrad.rst
4647
random.rst
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
:hide-toc:
2+
3+
MoDo
4+
====
5+
6+
.. autoclass:: torchjd.aggregation.MoDoWeighting
7+
:members: __call__, reset

‎docs/source/docs/scalarization/index.rst‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,4 +19,5 @@ Abstract base class
1919
geometric_mean.rst
2020
mean.rst
2121
random.rst
22+
stch.rst
2223
sum.rst
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
:hide-toc:
2+
3+
STCH
4+
====
5+
6+
.. autoclass:: torchjd.scalarization.STCH
7+
:members: __call__

‎src/torchjd/aggregation/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@
5353
from ._mean import Mean, MeanWeighting
5454
from ._mgda import MGDA, MGDAWeighting
5555
from ._mixins import Stateful
56+
from ._modo import MoDoWeighting
5657
from ._nash_mtl import NashMTL
5758
from ._pcgrad import PCGrad, PCGradWeighting
5859
from ._random import Random, RandomWeighting
@@ -87,6 +88,7 @@
8788
"MeanWeighting",
8889
"MGDA",
8990
"MGDAWeighting",
91+
"MoDoWeighting",
9092
"NashMTL",
9193
"PCGrad",
9294
"PCGradWeighting",

‎src/torchjd/aggregation/_modo.py‎

Lines changed: 197 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,197 @@
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})"

‎src/torchjd/scalarization/__init__.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
from ._mean import Mean
2525
from ._random import Random
2626
from ._scalarizer_base import Scalarizer
27+
from ._stch import STCH
2728
from ._sum import Sum
2829

29-
__all__ = ["Constant", "GeometricMean", "Mean", "Random", "Scalarizer", "Sum"]
30+
__all__ = ["Constant", "GeometricMean", "Mean", "Random", "Scalarizer", "STCH", "Sum"]

‎src/torchjd/scalarization/_stch.py‎

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
import torch
2+
from torch import Tensor
3+
4+
from ._scalarizer_base import Scalarizer
5+
6+
7+
class STCH(Scalarizer):
8+
r"""
9+
:class:`~torchjd.scalarization.Scalarizer` that combines the input tensor of values using smooth
10+
Tchebycheff scalarization, as defined in `Smooth Tchebycheff Scalarization for Multi-Objective
11+
Optimization <https://openreview.net/pdf?id=m4dO5L6eCp>`_.
12+
13+
It returns
14+
15+
.. math::
16+
\mu \log \sum_{i=1}^m \exp\left(\frac{\lambda_i (f_i - z_i^*)}{\mu}\right),
17+
18+
a smooth approximation of the (non-differentiable) weighted maximum
19+
:math:`\max_i \lambda_i (f_i - z_i^*)` that becomes tighter as ``mu`` decreases.
20+
21+
Following the paper's notation:
22+
23+
- :math:`f_i` is the :math:`i`-th input value (the :math:`i`-th objective),
24+
- :math:`m` is the number of objectives (the number of elements of the input),
25+
- :math:`\lambda_i` is its preference weight (the ``weights`` parameter),
26+
- :math:`z_i^*` is the :math:`i`-th component of the ideal point (the ``reference`` parameter),
27+
- :math:`\mu` is the smoothing parameter (the ``mu`` parameter).
28+
29+
:param mu: The smoothing parameter :math:`\mu`. Must be strictly positive. Smaller values make
30+
the scalarization closer to the maximum. The paper evaluates :math:`\mu \in \{0.01, 0.1,
31+
0.5, 1\}` and reports that a small :math:`\mu` works reasonably well, while no single value
32+
is best across all problems.
33+
:param weights: The preference vector :math:`\lambda` applied to the values (in the paper, on
34+
the probability simplex). If ``None``, a uniform preference summing to one is used. If
35+
provided, it must have the same shape as the values passed at call time.
36+
:param reference: The ideal point :math:`z^*` subtracted from the values. If ``None``, no shift
37+
is applied. If provided, it must have the same shape as the values passed at call time.
38+
"""
39+
40+
def __init__(
41+
self,
42+
mu: float,
43+
weights: Tensor | None = None,
44+
reference: Tensor | None = None,
45+
) -> None:
46+
if mu <= 0.0:
47+
raise ValueError(f"Parameter `mu` should be strictly positive. Found `mu = {mu}`.")
48+
49+
super().__init__()
50+
self.mu = mu
51+
self.weights = weights
52+
self.reference = reference
53+
54+
def forward(self, values: Tensor, /) -> Tensor:
55+
if self.weights is not None and self.weights.shape != values.shape:
56+
raise ValueError(
57+
f"Parameter `weights` should have the same shape as `values`. Found "
58+
f"`weights.shape = {tuple(self.weights.shape)}` and `values.shape = "
59+
f"{tuple(values.shape)}`."
60+
)
61+
if self.reference is not None and self.reference.shape != values.shape:
62+
raise ValueError(
63+
f"Parameter `reference` should have the same shape as `values`. Found "
64+
f"`reference.shape = {tuple(self.reference.shape)}` and `values.shape = "
65+
f"{tuple(values.shape)}`."
66+
)
67+
68+
if self.weights is None:
69+
weights = torch.full_like(values, 1.0 / values.numel())
70+
else:
71+
weights = self.weights
72+
73+
shifted = values if self.reference is None else values - self.reference
74+
75+
# Center the weighted values before dividing by mu (Appendix B.1 of the paper). This keeps
76+
# the largest exponent at 0 so the `/ mu` step never overflows for large values and small
77+
# mu. Adding `max_y` back makes it value-preserving: the result and its gradient are
78+
# mathematically identical to `mu * logsumexp(weights * shifted / mu)`.
79+
y = weights * shifted
80+
max_y = y.max()
81+
exponents = (y - max_y) / self.mu
82+
return self.mu * torch.logsumexp(exponents.flatten(), dim=-1) + max_y
83+
84+
def __repr__(self) -> str:
85+
return (
86+
f"{self.__class__.__name__}(mu={self.mu}, weights={self.weights!r}, "
87+
f"reference={self.reference!r})"
88+
)

0 commit comments

Comments
 (0)