Skip to content

Commit 57974a0

Browse files
feat(aggregation): Add MoDoWeighting (#717)
Theory: [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). Implementation adapted from LibMTL.
1 parent dbfe8f7 commit 57974a0

7 files changed

Lines changed: 423 additions & 0 deletions

File tree

‎CHANGELOG.md‎

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

1111
### Added
1212

13+
- 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`.
1314
- Added `GeometricMean` (also known as GLS) studied in [MultiNet++: Multi-Stream Feature
1415
Aggregation and Geometric Loss Strategy for Multi-Task
1516
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

‎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})"

0 commit comments

Comments
 (0)