Skip to content

Commit d1973e7

Browse files
authored
refactor(aggregation): Add _NonDifferentiable mixin (#677)
* Make non-differentiable aggregators inherit from _NonDifferentiable * Stop raising error when trying to differentiate through a non-differentiable weighting: we won't be able to do that anyway now * Update test_non_differentiable * Add changelog entry
1 parent ab099a2 commit d1973e7

13 files changed

Lines changed: 66 additions & 69 deletions

File tree

‎CHANGELOG.md‎

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

99
## [Unreleased]
1010

11+
### Changed
12+
13+
- Non-differentiable aggregators and weightings (UPGrad, DualProj, PCGrad, GradVac, IMTLG,
14+
GradDrop, ConFIG, CAGrad, NashMTL) no longer build a computation graph when called on tensors
15+
that require gradients. Their forward pass is now wrapped in `torch.no_grad()`, so attempting to
16+
differentiate through them is not possible anymore (while before, it raised a `NonDifferentiableError`).
17+
1118
### Added
1219

1320
- Made `WeightedAggregator` and `GramianWeightedAggregator` public. These abstract base classes are

‎src/torchjd/aggregation/_cagrad.py‎

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from torchjd.linalg import PSDMatrix
44

5+
from ._mixins import _NonDifferentiable
56
from ._utils.check_dependencies import check_dependencies_are_installed
67
from ._weighting_bases import _GramianWeighting
78

@@ -15,10 +16,10 @@
1516
from torchjd._linalg import normalize
1617

1718
from ._aggregator_bases import GramianWeightedAggregator
18-
from ._utils.non_differentiable import raise_non_differentiable_error
1919

2020

21-
class CAGradWeighting(_GramianWeighting):
21+
# Non-differentiable: the cvxpy solver operates on numpy arrays, breaking the autograd graph.
22+
class CAGradWeighting(_NonDifferentiable, _GramianWeighting):
2223
"""
2324
:class:`~torchjd.aggregation.Weighting` [:class:`~torchjd.linalg.PSDMatrix`]
2425
giving the weights of :class:`~torchjd.aggregation.CAGrad`.
@@ -92,7 +93,7 @@ def norm_eps(self, value: float) -> None:
9293
self._norm_eps = value
9394

9495

95-
class CAGrad(GramianWeightedAggregator):
96+
class CAGrad(_NonDifferentiable, GramianWeightedAggregator):
9697
"""
9798
:class:`~torchjd.aggregation.GramianWeightedAggregator` as defined in Algorithm 1 of
9899
`Conflict-Averse Gradient Descent for Multi-task Learning
@@ -113,9 +114,6 @@ class CAGrad(GramianWeightedAggregator):
113114
def __init__(self, c: float, norm_eps: float = 0.0001) -> None:
114115
super().__init__(CAGradWeighting(c=c, norm_eps=norm_eps))
115116

116-
# This prevents considering the computed weights as constant w.r.t. the matrix.
117-
self.register_full_backward_pre_hook(raise_non_differentiable_error)
118-
119117
@property
120118
def c(self) -> float:
121119
return self.gramian_weighting.c

‎src/torchjd/aggregation/_config.py‎

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,13 @@
88
from torchjd.linalg import Matrix
99

1010
from ._aggregator_bases import Aggregator
11+
from ._mixins import _NonDifferentiable
1112
from ._sum import SumWeighting
12-
from ._utils.non_differentiable import raise_non_differentiable_error
1313
from ._utils.pref_vector import pref_vector_to_str_suffix, pref_vector_to_weighting
1414

1515

16-
class ConFIG(Aggregator):
16+
# Non-differentiable: the pseudoinverse and the normalization are not differentiable in this context.
17+
class ConFIG(_NonDifferentiable, Aggregator):
1718
"""
1819
:class:`~torchjd.aggregation.Aggregator` as defined in Equation 2 of `ConFIG:
1920
Towards Conflict-free Training of Physics Informed Neural Networks
@@ -31,9 +32,6 @@ def __init__(self, pref_vector: Tensor | None = None) -> None:
3132
super().__init__()
3233
self.pref_vector = pref_vector
3334

34-
# This prevents computing gradients that can be very wrong.
35-
self.register_full_backward_pre_hook(raise_non_differentiable_error)
36-
3735
def forward(self, matrix: Matrix, /) -> Tensor:
3836
weights = self.weighting(matrix)
3937
units = torch.nan_to_num((matrix / (matrix.norm(dim=1)).unsqueeze(1)), 0.0)

‎src/torchjd/aggregation/_dualproj.py‎

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,14 @@
55

66
from ._aggregator_bases import GramianWeightedAggregator
77
from ._mean import MeanWeighting
8+
from ._mixins import _NonDifferentiable
89
from ._utils.dual_cone import SUPPORTED_SOLVER, project_weights
9-
from ._utils.non_differentiable import raise_non_differentiable_error
1010
from ._utils.pref_vector import pref_vector_to_str_suffix, pref_vector_to_weighting
1111
from ._weighting_bases import _GramianWeighting
1212

1313

14-
class DualProjWeighting(_GramianWeighting):
14+
# Non-differentiable: the QP solver operates on numpy arrays, breaking the autograd graph.
15+
class DualProjWeighting(_NonDifferentiable, _GramianWeighting):
1516
r"""
1617
:class:`~torchjd.aggregation.Weighting` [:class:`~torchjd.linalg.PSDMatrix`]
1718
giving the weights of :class:`~torchjd.aggregation.DualProj`.
@@ -77,7 +78,7 @@ def reg_eps(self, value: float) -> None:
7778
self._reg_eps = value
7879

7980

80-
class DualProj(GramianWeightedAggregator):
81+
class DualProj(_NonDifferentiable, GramianWeightedAggregator):
8182
r"""
8283
:class:`~torchjd.aggregation.GramianWeightedAggregator` that averages the rows of the input
8384
matrix, and projects the result onto the dual cone of the rows of the matrix. This corresponds
@@ -109,9 +110,6 @@ def __init__(
109110
DualProjWeighting(pref_vector, norm_eps=norm_eps, reg_eps=reg_eps, solver=solver),
110111
)
111112

112-
# This prevents considering the computed weights as constant w.r.t. the matrix.
113-
self.register_full_backward_pre_hook(raise_non_differentiable_error)
114-
115113
@property
116114
def pref_vector(self) -> Tensor | None:
117115
return self.gramian_weighting.pref_vector

‎src/torchjd/aggregation/_graddrop.py‎

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,15 @@
66
from torchjd.linalg import Matrix
77

88
from ._aggregator_bases import Aggregator
9-
from ._utils.non_differentiable import raise_non_differentiable_error
9+
from ._mixins import _NonDifferentiable
1010

1111

1212
def _identity(P: Tensor) -> Tensor:
1313
return P
1414

1515

16-
class GradDrop(Aggregator):
16+
# Non-differentiable: the sign-based random masking is not differentiable.
17+
class GradDrop(_NonDifferentiable, Aggregator):
1718
"""
1819
:class:`~torchjd.aggregation.Aggregator` that applies the gradient combination
1920
steps from GradDrop, as defined in lines 10 to 15 of Algorithm 1 of `Just Pick a Sign:
@@ -31,9 +32,6 @@ def __init__(self, f: Callable = _identity, leak: Tensor | None = None) -> None:
3132
self.f = f
3233
self.leak = leak
3334

34-
# This prevents computing gradients that can be very wrong.
35-
self.register_full_backward_pre_hook(raise_non_differentiable_error)
36-
3735
def forward(self, matrix: Matrix, /) -> Tensor:
3836
self._check_matrix_has_enough_rows(matrix)
3937

‎src/torchjd/aggregation/_gradvac.py‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,15 @@
55
import torch
66
from torch import Tensor
77

8-
from torchjd.aggregation._mixins import Stateful
8+
from torchjd.aggregation._mixins import Stateful, _NonDifferentiable
99
from torchjd.linalg import PSDMatrix
1010

1111
from ._aggregator_bases import GramianWeightedAggregator
12-
from ._utils.non_differentiable import raise_non_differentiable_error
1312
from ._weighting_bases import _GramianWeighting
1413

1514

16-
class GradVacWeighting(_GramianWeighting, Stateful):
15+
# Non-differentiable: weights are modified in-place during the gradient correction loop.
16+
class GradVacWeighting(_NonDifferentiable, Stateful, _GramianWeighting):
1717
r"""
1818
:class:`~torchjd.aggregation._mixins.Stateful`
1919
:class:`~torchjd.aggregation.Weighting` [:class:`~torchjd.linalg.PSDMatrix`]
@@ -128,7 +128,7 @@ def _ensure_state(self, m: int, dtype: torch.dtype) -> None:
128128
self._state_key = key
129129

130130

131-
class GradVac(GramianWeightedAggregator, Stateful):
131+
class GradVac(_NonDifferentiable, Stateful, GramianWeightedAggregator):
132132
r"""
133133
:class:`~torchjd.aggregation._mixins.Stateful`
134134
:class:`~torchjd.aggregation.GramianWeightedAggregator` implementing the aggregation step of
@@ -167,7 +167,6 @@ def __init__(self, beta: float = 0.5, eps: float = 1e-8) -> None:
167167
weighting = GradVacWeighting(beta=beta, eps=eps)
168168
super().__init__(weighting)
169169
self._gradvac_weighting = weighting
170-
self.register_full_backward_pre_hook(raise_non_differentiable_error)
171170

172171
@property
173172
def beta(self) -> float:

‎src/torchjd/aggregation/_imtl_g.py‎

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,12 @@
44
from torchjd.linalg import PSDMatrix
55

66
from ._aggregator_bases import GramianWeightedAggregator
7-
from ._utils.non_differentiable import raise_non_differentiable_error
7+
from ._mixins import _NonDifferentiable
88
from ._weighting_bases import _GramianWeighting
99

1010

11-
class IMTLGWeighting(_GramianWeighting):
11+
# Non-differentiable: differentiating through pinv(gramian) would give incorrect gradients.
12+
class IMTLGWeighting(_NonDifferentiable, _GramianWeighting):
1213
"""
1314
:class:`~torchjd.aggregation.Weighting` [:class:`~torchjd.linalg.PSDMatrix`]
1415
giving the weights of :class:`~torchjd.aggregation.IMTLG`.
@@ -24,7 +25,7 @@ def forward(self, gramian: PSDMatrix, /) -> Tensor:
2425
return weights
2526

2627

27-
class IMTLG(GramianWeightedAggregator):
28+
class IMTLG(_NonDifferentiable, GramianWeightedAggregator):
2829
"""
2930
:class:`~torchjd.aggregation.GramianWeightedAggregator` generalizing the method described in
3031
`Towards Impartial Multi-task Learning <https://discovery.ucl.ac.uk/id/eprint/10120667/>`_.
@@ -36,6 +37,3 @@ class IMTLG(GramianWeightedAggregator):
3637

3738
def __init__(self) -> None:
3839
super().__init__(IMTLGWeighting())
39-
40-
# This prevents computing gradients that can be very wrong.
41-
self.register_full_backward_pre_hook(raise_non_differentiable_error)

‎src/torchjd/aggregation/_mixins.py‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
11
from abc import ABC, abstractmethod
2+
from typing import Any
3+
4+
import torch
5+
from torch import nn
26

37

48
class Stateful(ABC):
@@ -7,3 +11,19 @@ class Stateful(ABC):
711
@abstractmethod
812
def reset(self) -> None:
913
"""Resets the internal state."""
14+
15+
16+
class _NonDifferentiable(nn.Module):
17+
"""
18+
Mixin making a nn.Module non-differentiable, preventing autograd graph construction by wrapping
19+
the call in :func:`torch.no_grad`.
20+
21+
.. warning::
22+
This mixin must appear **before** any :class:`torch.nn.Module` base class in the inheritance
23+
list. Placing it after will silently have no effect, because :meth:`__call__` would be
24+
resolved to :class:`torch.nn.Module` before reaching this mixin.
25+
"""
26+
27+
def __call__(self, *args: Any, **kwargs: Any) -> Any:
28+
with torch.no_grad():
29+
return super().__call__(*args, **kwargs)

‎src/torchjd/aggregation/_nash_mtl.py‎

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
# Partly adapted from https://github.com/AvivNavon/nash-mtl — MIT License, Copyright (c) 2022 Aviv Navon.
22
# See NOTICES for the full license text.
33

4-
from torchjd.aggregation._mixins import Stateful
4+
from torchjd.aggregation._mixins import Stateful, _NonDifferentiable
55

66
from ._utils.check_dependencies import check_dependencies_are_installed
77
from ._weighting_bases import _MatrixWeighting
@@ -15,10 +15,10 @@
1515
from torch import Tensor
1616

1717
from ._aggregator_bases import WeightedAggregator
18-
from ._utils.non_differentiable import raise_non_differentiable_error
1918

2019

21-
class _NashMTLWeighting(_MatrixWeighting, Stateful):
20+
# Non-differentiable: the cvxpy solver operates on numpy arrays, breaking the autograd graph.
21+
class _NashMTLWeighting(_NonDifferentiable, Stateful, _MatrixWeighting):
2222
"""
2323
:class:`~torchjd.aggregation._mixins.Stateful`
2424
:class:`~torchjd.aggregation.Weighting` [:class:`~torchjd.linalg.Matrix`] that
@@ -199,7 +199,7 @@ def reset(self) -> None:
199199
self.prvs_alpha = np.ones(self.n_tasks, dtype=np.float32)
200200

201201

202-
class NashMTL(WeightedAggregator, Stateful):
202+
class NashMTL(_NonDifferentiable, Stateful, WeightedAggregator):
203203
"""
204204
:class:`~torchjd.aggregation._mixins.Stateful`
205205
:class:`~torchjd.aggregation.WeightedAggregator` as proposed in Algorithm 1 of
@@ -253,9 +253,6 @@ def __init__(
253253
),
254254
)
255255

256-
# This prevents considering the computed weights as constant w.r.t. the matrix.
257-
self.register_full_backward_pre_hook(raise_non_differentiable_error)
258-
259256
@property
260257
def n_tasks(self) -> int:
261258
return self.weighting.n_tasks

‎src/torchjd/aggregation/_pcgrad.py‎

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,12 @@
66
from torchjd.linalg import PSDMatrix
77

88
from ._aggregator_bases import GramianWeightedAggregator
9-
from ._utils.non_differentiable import raise_non_differentiable_error
9+
from ._mixins import _NonDifferentiable
1010
from ._weighting_bases import _GramianWeighting
1111

1212

13-
class PCGradWeighting(_GramianWeighting):
13+
# Non-differentiable: weights are modified in-place during the gradient projection loop.
14+
class PCGradWeighting(_NonDifferentiable, _GramianWeighting):
1415
"""
1516
:class:`~torchjd.aggregation.Weighting` [:class:`~torchjd.linalg.PSDMatrix`]
1617
giving the weights of :class:`~torchjd.aggregation.PCGrad`.
@@ -46,7 +47,7 @@ def forward(self, gramian: PSDMatrix, /) -> Tensor:
4647
return weights.to(device)
4748

4849

49-
class PCGrad(GramianWeightedAggregator):
50+
class PCGrad(_NonDifferentiable, GramianWeightedAggregator):
5051
"""
5152
:class:`~torchjd.aggregation.GramianWeightedAggregator` as defined in Algorithm 1 of
5253
`Gradient Surgery for Multi-Task Learning <https://arxiv.org/pdf/2001.06782.pdf>`_.
@@ -56,6 +57,3 @@ class PCGrad(GramianWeightedAggregator):
5657

5758
def __init__(self) -> None:
5859
super().__init__(PCGradWeighting())
59-
60-
# This prevents running into a RuntimeError due to modifying stored tensors in place.
61-
self.register_full_backward_pre_hook(raise_non_differentiable_error)

0 commit comments

Comments
 (0)