Skip to content

Commit fcc19d3

Browse files
refactor!: Add DualConeProjector (#678)
Add `DualConeProjector` and `QuadprogProjector` to represent the method to solve QPs in UPGrad and DualProj. QP related parameters (`reg_eps` and `norm_eps`) responsibilities are now delegated to subclasses of `DualConeProjector`. Co-authored-by: Valérian Rey <valerian.rey@gmail.com>
1 parent edf5272 commit fcc19d3

14 files changed

Lines changed: 308 additions & 332 deletions

File tree

‎CHANGELOG.md‎

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

1111
### Changed
1212

13+
- **BREAKING**: Removed `norm_eps`, `rep_eps` and `solver` parameters from the `__init__` of
14+
`UPGrad`, `UPGradWeighting`, `DualProj` and `DualProjWeighting` in favor of a `projector`
15+
parameter of type `DualConeProjector`. To update:
16+
```python
17+
# Before
18+
from torchjd.aggregation import UPGrad
19+
aggregator = UPGrad(norm_eps=1e-6, reg_eps=1e-6, solver="quadprog")
20+
21+
# After
22+
from torchjd.aggregation import UPGrad
23+
from torchjd.linalg import QuadprogProjector
24+
aggregator = UPGrad(projector=QuadprogProjector(norm_eps=1e-6, reg_eps=1e-6))
25+
```
26+
If you used the default `norm_eps`, `reg_eps` and `solver`, you don't have to change anything and
27+
you will get the same results.
1328
- `CAGrad`, `CAGradWeighting`, and `NashMTL` are now always importable from `torchjd.aggregation`,
1429
even when their optional dependencies are not installed. Attempting to instantiate them without the
1530
required dependencies now raises an `ImportError` with installation instructions, instead of
@@ -21,6 +36,9 @@ changelog does not include internal changes that do not affect the user.
2136

2237
### Added
2338

39+
- Added a new abstraction: the `DualConeProjector` abstract base class and its concrete
40+
`QuadprogProjector` implementation, to do the projection of the gradients onto the dual cone, as
41+
required in `UPGrad`, and `DualProj`. These classes can be found in `torchjd.linalg`.
2442
- Made `WeightedAggregator` and `GramianWeightedAggregator` public. These abstract base classes are
2543
now importable from `torchjd.aggregation` and documented. They can be extended to easily implement
2644
custom `Aggregator`s.
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
:hide-toc:
2+
3+
Dual Cone Projectors
4+
====================
5+
6+
.. autoclass:: torchjd.linalg.DualConeProjector
7+
:members: __call__
8+
9+
.. autoclass:: torchjd.linalg.QuadprogProjector

‎docs/source/docs/linalg/index.rst‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,3 +10,4 @@ linalg
1010

1111
matrix.rst
1212
psd_matrix.rst
13+
dual_cone.rst

‎src/torchjd/_linalg/__init__.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
from ._dual_cone import DualConeProjector, QuadprogProjector, projector_or_default
12
from ._generalized_gramian import flatten, movedim, reshape
23
from ._gramian import compute_gramian, normalize, regularize
34
from ._matrix import Matrix, PSDMatrix, PSDTensor, is_matrix, is_psd_matrix, is_psd_tensor
@@ -15,4 +16,7 @@
1516
"flatten",
1617
"reshape",
1718
"movedim",
19+
"DualConeProjector",
20+
"QuadprogProjector",
21+
"projector_or_default",
1822
]

‎src/torchjd/_linalg/_dual_cone.py‎

Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
from abc import ABC, abstractmethod
2+
3+
import numpy as np
4+
import torch
5+
from qpsolvers import solve_qp
6+
from torch import Tensor
7+
8+
from ._gramian import normalize, regularize
9+
from ._matrix import PSDMatrix
10+
11+
12+
class DualConeProjector(ABC):
13+
"""
14+
Abstract class whose instances are responsible for projecting vectors onto the dual cone of the
15+
rows of a matrix, or rather the dual form of this problem.
16+
"""
17+
18+
@abstractmethod
19+
def __call__(self, U: Tensor, G: PSDMatrix) -> Tensor:
20+
r"""
21+
Computes for each vector :math:`u` in the provided tensor ``U``
22+
the weights :math:`w` of the projection of :math:`J^\top u` onto the dual cone of
23+
the rows of :math:`J`, provided :math:`G = J J^\top` and :math:`u`. In other words, this
24+
computes the :math:`w` that satisfies :math:`\pi_J(J^\top u) = J^\top w`, with
25+
:math:`\pi_J` defined in Equation 3 of [1].
26+
27+
By Proposition 1 of [1], this is equivalent to solving for :math:`v` the following
28+
quadratic program:
29+
30+
.. math::
31+
32+
\min_{v} \quad & v^\top G v \\
33+
\text{subject to} \quad & u \preceq v
34+
35+
Reference:
36+
[1] `Jacobian Descent For Multi-Objective Optimization <https://arxiv.org/pdf/2406.16232>`_.
37+
38+
:param U: The tensor of weights corresponding to the vectors to project, of shape
39+
``[..., m]``.
40+
:param G: The Gramian matrix of shape ``[m, m]``. It must be symmetric and positive
41+
semi-definite.
42+
:return: A tensor of projection weights with the same shape as ``U``.
43+
"""
44+
45+
46+
def projector_or_default(projector: DualConeProjector | None) -> DualConeProjector:
47+
if projector is None:
48+
return QuadprogProjector()
49+
return projector
50+
51+
52+
class QuadprogProjector(DualConeProjector):
53+
r"""
54+
Solves the quadratic program defined in :meth:`DualConeProjector.__call__` using the
55+
`quadprog <https://github.com/quadprog/quadprog>`_ QP solver.
56+
57+
:param norm_eps: A small value to avoid division by zero when normalizing.
58+
:param reg_eps: A small value to add to the diagonal of the gramian of the matrix. Due to
59+
numerical errors when computing the gramian, it might not exactly be positive definite.
60+
This issue can make the optimization fail. Adding ``reg_eps`` to the diagonal of the gramian
61+
ensures that it is positive definite.
62+
"""
63+
64+
def __init__(
65+
self,
66+
*,
67+
norm_eps: float = 0.0001,
68+
reg_eps: float = 0.0001,
69+
) -> None:
70+
self._norm_eps = norm_eps
71+
self._reg_eps = reg_eps
72+
73+
@property
74+
def norm_eps(self) -> float:
75+
return self._norm_eps
76+
77+
@norm_eps.setter
78+
def norm_eps(self, value: float) -> None:
79+
if value < 0.0:
80+
raise ValueError(f"norm_eps must be non-negative, but got {value}.")
81+
self._norm_eps = value
82+
83+
@property
84+
def reg_eps(self) -> float:
85+
return self._reg_eps
86+
87+
@reg_eps.setter
88+
def reg_eps(self, value: float) -> None:
89+
if value < 0.0:
90+
raise ValueError(f"reg_eps must be non-negative, but got {value}.")
91+
self._reg_eps = value
92+
93+
def __repr__(self) -> str:
94+
return f"QuadprogProjector(norm_eps={self._norm_eps}, reg_eps={self._reg_eps})"
95+
96+
def __call__(self, U: Tensor, G: PSDMatrix) -> Tensor:
97+
98+
G = regularize(normalize(G, self._norm_eps), self._reg_eps)
99+
100+
G_ = _to_array(G)
101+
U_ = _to_array(U)
102+
103+
W = np.apply_along_axis(lambda u: self._project_weight_vector(u, G_), axis=-1, arr=U_)
104+
105+
return torch.as_tensor(W, device=G.device, dtype=G.dtype)
106+
107+
def _project_weight_vector(self, u: np.ndarray, G: np.ndarray) -> np.ndarray:
108+
109+
m = G.shape[0]
110+
w = solve_qp(G, np.zeros(m), -np.eye(m), -u, solver="quadprog")
111+
112+
if w is None: # This may happen when G has large values.
113+
raise ValueError("Failed to solve the quadratic programming problem.")
114+
115+
return w
116+
117+
118+
def _to_array(tensor: Tensor) -> np.ndarray:
119+
"""Transforms a tensor into a numpy array with float64 dtype."""
120+
121+
return tensor.cpu().detach().numpy().astype(np.float64)

‎src/torchjd/aggregation/_dualproj.py‎

Lines changed: 20 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,11 @@
11
from torch import Tensor
22

3-
from torchjd._linalg import normalize, regularize
3+
from torchjd._linalg import DualConeProjector, projector_or_default
44
from torchjd.linalg import PSDMatrix
55

66
from ._aggregator_bases import GramianWeightedAggregator
77
from ._mean import MeanWeighting
88
from ._mixins import _NonDifferentiable
9-
from ._utils.dual_cone import SUPPORTED_SOLVER, project_weights
109
from ._utils.pref_vector import pref_vector_to_str_suffix, pref_vector_to_weighting
1110
from ._weighting_bases import _GramianWeighting
1211

@@ -19,31 +18,21 @@ class DualProjWeighting(_NonDifferentiable, _GramianWeighting):
1918
2019
:param pref_vector: The preference vector to use. If not provided, defaults to
2120
:math:`\begin{bmatrix} \frac{1}{m} & \dots & \frac{1}{m} \end{bmatrix}^T \in \mathbb{R}^m`.
22-
:param norm_eps: A small value to avoid division by zero when normalizing.
23-
:param reg_eps: A small value to add to the diagonal of the gramian of the matrix. Due to
24-
numerical errors when computing the gramian, it might not exactly be positive definite.
25-
This issue can make the optimization fail. Adding ``reg_eps`` to the diagonal of the gramian
26-
ensures that it is positive definite.
27-
:param solver: The solver used to optimize the underlying optimization problem.
21+
:param projector: The :class:`~torchjd.linalg.DualConeProjector` used to compute the projection.
2822
"""
2923

3024
def __init__(
3125
self,
3226
pref_vector: Tensor | None = None,
33-
norm_eps: float = 0.0001,
34-
reg_eps: float = 0.0001,
35-
solver: SUPPORTED_SOLVER = "proxsuite",
27+
projector: DualConeProjector | None = None,
3628
) -> None:
3729
super().__init__()
3830
self.pref_vector = pref_vector
39-
self.norm_eps = norm_eps
40-
self.reg_eps = reg_eps
41-
self.solver: SUPPORTED_SOLVER = solver
31+
self.projector = projector_or_default(projector)
4232

4333
def forward(self, gramian: PSDMatrix, /) -> Tensor:
4434
u = self.weighting(gramian)
45-
G = regularize(normalize(gramian, self.norm_eps), self.reg_eps)
46-
w = project_weights(u, G, self.solver)
35+
w = self.projector(u, gramian)
4736
return w
4837

4938
@property
@@ -56,26 +45,12 @@ def pref_vector(self, value: Tensor | None) -> None:
5645
self._pref_vector = value
5746

5847
@property
59-
def norm_eps(self) -> float:
60-
return self._norm_eps
48+
def projector(self) -> DualConeProjector:
49+
return self._projector
6150

62-
@norm_eps.setter
63-
def norm_eps(self, value: float) -> None:
64-
if value < 0:
65-
raise ValueError(f"norm_eps must be non-negative, but got {value}.")
66-
67-
self._norm_eps = value
68-
69-
@property
70-
def reg_eps(self) -> float:
71-
return self._reg_eps
72-
73-
@reg_eps.setter
74-
def reg_eps(self, value: float) -> None:
75-
if value < 0:
76-
raise ValueError(f"reg_eps must be non-negative, but got {value}.")
77-
78-
self._reg_eps = value
51+
@projector.setter
52+
def projector(self, value: DualConeProjector | None) -> None:
53+
self._projector = projector_or_default(value)
7954

8055

8156
class DualProj(_NonDifferentiable, GramianWeightedAggregator):
@@ -87,27 +62,18 @@ class DualProj(_NonDifferentiable, GramianWeightedAggregator):
8762
8863
:param pref_vector: The preference vector used to combine the rows. If not provided, defaults to
8964
:math:`\begin{bmatrix} \frac{1}{m} & \dots & \frac{1}{m} \end{bmatrix}^T \in \mathbb{R}^m`.
90-
:param norm_eps: A small value to avoid division by zero when normalizing.
91-
:param reg_eps: A small value to add to the diagonal of the gramian of the matrix. Due to
92-
numerical errors when computing the gramian, it might not exactly be positive definite.
93-
This issue can make the optimization fail. Adding ``reg_eps`` to the diagonal of the gramian
94-
ensures that it is positive definite.
95-
:param solver: The solver used to optimize the underlying optimization problem.
65+
:param projector: The :class:`~torchjd.linalg.DualConeProjector` used to compute the projection.
9666
"""
9767

9868
gramian_weighting: DualProjWeighting
9969

10070
def __init__(
10171
self,
10272
pref_vector: Tensor | None = None,
103-
norm_eps: float = 0.0001,
104-
reg_eps: float = 0.0001,
105-
solver: SUPPORTED_SOLVER = "proxsuite",
73+
projector: DualConeProjector | None = None,
10674
) -> None:
107-
self._solver: SUPPORTED_SOLVER = solver
108-
10975
super().__init__(
110-
DualProjWeighting(pref_vector, norm_eps=norm_eps, reg_eps=reg_eps, solver=solver),
76+
DualProjWeighting(pref_vector, projector=projector),
11177
)
11278

11379
@property
@@ -119,25 +85,17 @@ def pref_vector(self, value: Tensor | None) -> None:
11985
self.gramian_weighting.pref_vector = value
12086

12187
@property
122-
def norm_eps(self) -> float:
123-
return self.gramian_weighting.norm_eps
124-
125-
@norm_eps.setter
126-
def norm_eps(self, value: float) -> None:
127-
self.gramian_weighting.norm_eps = value
128-
129-
@property
130-
def reg_eps(self) -> float:
131-
return self.gramian_weighting.reg_eps
88+
def projector(self) -> DualConeProjector:
89+
return self.gramian_weighting.projector
13290

133-
@reg_eps.setter
134-
def reg_eps(self, value: float) -> None:
135-
self.gramian_weighting.reg_eps = value
91+
@projector.setter
92+
def projector(self, value: DualConeProjector | None) -> None:
93+
self.gramian_weighting.projector = value
13694

13795
def __repr__(self) -> str:
13896
return (
139-
f"{self.__class__.__name__}(pref_vector={repr(self.pref_vector)}, norm_eps="
140-
f"{self.norm_eps}, reg_eps={self.reg_eps}, solver={repr(self._solver)})"
97+
f"{self.__class__.__name__}(pref_vector={repr(self.pref_vector)}, projector="
98+
f"{repr(self.projector)})"
14199
)
142100

143101
def __str__(self) -> str:

0 commit comments

Comments
 (0)