Skip to content

Commit bb52b6f

Browse files
authored
test: Add trajectories in tests (#691)
1 parent cb1c680 commit bb52b6f

14 files changed

Lines changed: 1592 additions & 0 deletions

‎.gitignore‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,9 @@ CLAUDE.md
44
# Profiling results
55
traces/
66

7+
# Trajectories results
8+
tests/trajectories/results/
9+
710
# uv
811
uv.lock
912

‎CONTRIBUTING.md‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -228,6 +228,39 @@ implementation of a mathematical aggregator.
228228
To deprecate some public functionality, make it raise a `DeprecationWarning`. A test should also be
229229
added in `tests/unit/test_deprecations.py`, ensuring that this warning is issued.
230230
231+
## Trajectories
232+
233+
The `tests/trajectories/` directory contains scripts to generate and visualize optimization
234+
trajectories using various aggregators on simple multi-objective problems. They require the `plot`
235+
dependency group.
236+
237+
Available objective keys: `EWQ`, `CQF`, `CQF2`, `HQF`, `MN2`, `MN20`.
238+
239+
Available aggregator keys: `upgrad`, `mgda`, `cagrad`, `nashmtl`, `nashmtl20`, `graddrop`,
240+
`imtl_g`, `aligned_mtl`, `dualproj`, `pcgrad`, `random`, `mean`.
241+
242+
**Step 1 — Optimize:** run the optimization for an objective and a selection of aggregators:
243+
```bash
244+
uv run python tests/trajectories/optimize.py EWQ upgrad mean mgda cagrad dualproj graddrop imtl_g aligned_mtl nashmtl random
245+
```
246+
This saves trajectory data under `tests/trajectories/results/` (gitignored).
247+
248+
**Step 2 — Plot:** generate the plots from the saved trajectories:
249+
```bash
250+
export MPLBACKEND=Agg
251+
uv run python tests/trajectories/plot_params.py EWQ
252+
uv run python tests/trajectories/plot_values.py EWQ
253+
uv run python tests/trajectories/plot_distance_to_pf.py EWQ
254+
```
255+
256+
Replace `EWQ` with any other objective key. The three plot scripts produce PDFs saved to
257+
`tests/trajectories/results/<objective>/`.
258+
259+
> [!NOTE]
260+
> The plot scripts require a LaTeX installation for rendering:
261+
> `sudo apt-get install texlive-latex-extra texlive-fonts-recommended dvipng cm-super`
262+
263+
231264
## Release
232265
233266
*This section is addressed to maintainers.*

‎tests/trajectories/__init__.py‎

Whitespace-only changes.

‎tests/trajectories/_constants.py‎

Lines changed: 183 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,183 @@
1+
from math import cos, sin
2+
3+
import numpy as np
4+
import torch
5+
6+
from torchjd._linalg import QuadprogProjector
7+
from torchjd.aggregation import (
8+
IMTLG,
9+
MGDA,
10+
AlignedMTL,
11+
CAGrad,
12+
DualProj,
13+
GradDrop,
14+
Mean,
15+
NashMTL,
16+
PCGrad,
17+
Random,
18+
UPGrad,
19+
)
20+
from trajectories._objectives import (
21+
ConvexQuadraticForm,
22+
ElementWiseQuadratic,
23+
HomogenousQuadraticForm,
24+
Multinorm,
25+
QuadraticForm,
26+
)
27+
28+
AGGREGATORS = {
29+
"upgrad": UPGrad(projector=QuadprogProjector(reg_eps=1e-7, norm_eps=1e-9)),
30+
"mgda": MGDA(),
31+
"cagrad": CAGrad(c=0.5),
32+
"nashmtl": NashMTL(n_tasks=2, optim_niter=1),
33+
"nashmtl20": NashMTL(n_tasks=20, optim_niter=1),
34+
"graddrop": GradDrop(),
35+
"imtl_g": IMTLG(),
36+
"aligned_mtl": AlignedMTL(),
37+
"dualproj": DualProj(projector=QuadprogProjector(reg_eps=1e-7, norm_eps=1e-9)),
38+
"pcgrad": PCGrad(),
39+
"random": Random(),
40+
"mean": Mean(),
41+
}
42+
LR_MULTIPLIERS = {
43+
"upgrad": 1.0,
44+
"mgda": 2.0,
45+
"cagrad": 1.0,
46+
"nashmtl": 2.0,
47+
"nashmtl20": 2.0,
48+
"graddrop": 0.5,
49+
"imtl_g": 1.0,
50+
"aligned_mtl": 4.0,
51+
"dualproj": 1.0,
52+
"pcgrad": 0.5,
53+
"random": 1.0,
54+
"mean": 1.0,
55+
}
56+
# Some methods have optimal LRs that are very problem-specific. This allows overriding the LR
57+
# per-problem.
58+
LR_MULTIPLIER_OVERRIDES = {
59+
"HQF": {
60+
"nashmtl": 20.0,
61+
"imtl_g": 2.0,
62+
},
63+
"CQF": {"nashmtl": 0.5},
64+
"CQF2": {"nashmtl": 0.5},
65+
}
66+
AGGREGATOR_ORDER = {
67+
"upgrad": 9,
68+
"mgda": 1,
69+
"cagrad": 5,
70+
"nashmtl": 7,
71+
"nashmtl20": 7,
72+
"graddrop": 3,
73+
"imtl_g": 4,
74+
"aligned_mtl": 8,
75+
"dualproj": 2,
76+
"random": 6,
77+
"mean": 0,
78+
# No location for PCGrad as it's equivalent to UPGrad with 2 objectives
79+
}
80+
LATEX_NAMES = {
81+
"upgrad": r"$\mathcal A_{\mathrm{UPGrad}}$ (ours)",
82+
"mgda": r"$\mathcal A_{\mathrm{MGDA}}$",
83+
"cagrad": r"$\mathcal A_{\mathrm{CAGrad}}$",
84+
"nashmtl": r"$\mathcal A_{\mathrm{Nash-MTL}}$",
85+
"nashmtl20": r"$\mathcal A_{\mathrm{Nash-MTL}}$",
86+
"graddrop": r"$\mathcal A_{\mathrm{GradDrop}}$",
87+
"imtl_g": r"$\mathcal A_{\mathrm{IMTL-G}}$",
88+
"aligned_mtl": r"$\mathcal A_{\mathrm{Aligned-MTL}}$",
89+
"dualproj": r"$\mathcal A_{\mathrm{DualProj}}$",
90+
"pcgrad": r"$\mathcal A_{\mathrm{PCGrad}}$",
91+
"random": r"$\mathcal A_{\mathrm{RGW}}$",
92+
"mean": r"$\mathcal A_{\mathrm{Mean}}$",
93+
}
94+
95+
# Sometimes we need to override the xlim and ylim of the value plot to zoom enough
96+
PLOT_VALUES_LIMS = {
97+
"CQF": {
98+
"xlim": (-0.125, 2.625),
99+
"ylim": (-0.425, 8.925),
100+
},
101+
"CQF2": {
102+
"xlim": (-0.125, 2.625),
103+
"ylim": (-0.425, 8.925),
104+
},
105+
}
106+
107+
THETA = np.pi / 16
108+
109+
OBJECTIVES = {
110+
"EWQ": ElementWiseQuadratic(2),
111+
"CQF": ConvexQuadraticForm(
112+
Bs=[
113+
torch.tensor([[cos(THETA), -sin(THETA)], [sin(THETA), cos(THETA)]])
114+
@ torch.diag(torch.tensor([1.0, 0.1])),
115+
torch.tensor([[cos(THETA), sin(THETA)], [-sin(THETA), cos(THETA)]])
116+
@ torch.diag(torch.tensor([torch.sqrt(torch.tensor(3.0)), 0.1])),
117+
],
118+
us=[torch.tensor([1.0, 0.0]), torch.tensor([-1.0, 0.0])],
119+
),
120+
"CQF2": QuadraticForm(
121+
As=[torch.tensor([[1.0, 0.2], [0.2, 0.05]]), torch.tensor([[3.0, -0.6], [-0.6, 0.2]])],
122+
us=[torch.tensor([1.0, 0.0]), torch.tensor([-1.0, 0.0])],
123+
),
124+
"HQF": HomogenousQuadraticForm(
125+
A=torch.tensor([[2.0, -1.0], [-1.0, 2.0]]),
126+
scales=torch.tensor([1.0, 10.0]),
127+
us=[torch.tensor([1.0, 0.0]), torch.tensor([-10.0, 0.0])],
128+
),
129+
"MN2": Multinorm(torch.tensor([1.0, 10.0])),
130+
"MN20": Multinorm(torch.arange(1, 21)),
131+
}
132+
BASE_LEARNING_RATES = {
133+
"EWQ": 0.075,
134+
"CQF": 0.125,
135+
"CQF2": 0.125,
136+
"HQF": 0.005,
137+
"MN2": 0.02,
138+
"MN20": 0.005,
139+
}
140+
INITIAL_POINTS = {
141+
"EWQ": [
142+
[3.0, -2.0],
143+
[0.0, -3.0],
144+
[-4.0, 4.0],
145+
[-3.0, 4.0],
146+
[-3.5, -0.75],
147+
],
148+
"CQF": [
149+
[0.5, 0.5],
150+
[-1.0, 7.0],
151+
[0.0, 0.0],
152+
[1.0, 6.0],
153+
],
154+
"CQF2": [
155+
[0.5, 0.5],
156+
[-0.3, 7.0],
157+
[0.0, 0.0],
158+
],
159+
"HQF": [
160+
[-6.0, 4.0],
161+
[-3.0, -1.5],
162+
[1.5, 2.0],
163+
[2.5, 5.5],
164+
],
165+
"MN2": [
166+
[0.0, 0.0],
167+
[-5.0, 5.0],
168+
[10.0, 5.0],
169+
[10.0, 0.0],
170+
[20.0, 0.0],
171+
],
172+
"MN20": [
173+
[0.0] * 20,
174+
],
175+
}
176+
N_ITERS = {
177+
"EWQ": 50,
178+
"CQF": 200,
179+
"CQF2": 200,
180+
"HQF": 100,
181+
"MN2": 50,
182+
"MN20": 500,
183+
}

‎tests/trajectories/_objectives.py‎

Lines changed: 162 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,162 @@
1+
from abc import ABC, abstractmethod
2+
3+
import torch
4+
from torch import Tensor
5+
6+
7+
class Objective(ABC):
8+
def __init__(self, n_params: int, n_values: int) -> None:
9+
self.n_params = n_params
10+
self.n_values = n_values
11+
12+
@abstractmethod
13+
def __call__(self, x: Tensor) -> Tensor:
14+
"""Compute the value of the objective function at x. It has to be a vector."""
15+
16+
@abstractmethod
17+
def jacobian(self, x: Tensor) -> Tensor:
18+
"""
19+
Compute the value of the Jacobian of the objective function at x. It is a matrix of shape
20+
[n_values, n_params].
21+
"""
22+
23+
def __str__(self) -> str:
24+
"""Return a string representation of the objective function."""
25+
return self.__class__.__name__
26+
27+
def __repr__(self) -> str:
28+
return f"{self.__class__.__name__}({self.n_values})"
29+
30+
31+
class WithSPSMappingMixin(ABC):
32+
"""Mixin adding the possibility to get the Strong Pareto stationary mapping."""
33+
34+
class SPSMapping(ABC):
35+
@abstractmethod
36+
def __call__(self, w: Tensor) -> Tensor:
37+
"""
38+
Map a vector with (strictly) positive coordinates to the corresponding strongly pareto
39+
stationary point.
40+
"""
41+
42+
@property
43+
@abstractmethod
44+
def sps_mapping(self) -> "WithSPSMappingMixin.SPSMapping":
45+
pass
46+
47+
48+
class QuadraticForm(Objective, WithSPSMappingMixin):
49+
def __init__(self, As: list[Tensor], us: list[Tensor]) -> None:
50+
if len(As) != len(us):
51+
raise ValueError("As and us must have the same length.")
52+
53+
if len(As) < 1:
54+
raise ValueError("As and us must have at least one element.")
55+
56+
super().__init__(n_params=len(us[0]), n_values=len(As))
57+
# Note that if A is not PSD, the objective is not convex.
58+
self.As = As
59+
self.us = us
60+
61+
def __call__(self, x: Tensor) -> Tensor:
62+
objective_values = [self.quad(x, A, u) for A, u in zip(self.As, self.us, strict=False)]
63+
return torch.stack(objective_values)
64+
65+
def jacobian(self, x: Tensor) -> Tensor:
66+
return torch.vstack([2 * (x - u) @ A for A, u in zip(self.As, self.us, strict=False)])
67+
68+
def __repr__(self) -> str:
69+
return f"{self.__class__.__name__}(As={self.As}, us={self.us})"
70+
71+
@staticmethod
72+
def quad(x: Tensor, A: Tensor, u: Tensor) -> Tensor:
73+
x_minus_u = x - u
74+
return x_minus_u @ A @ x_minus_u
75+
76+
class SPSMapping(WithSPSMappingMixin.SPSMapping):
77+
def __init__(self, As: list[Tensor], us: list[Tensor]) -> None:
78+
self.As = As
79+
self.us = us
80+
81+
def __call__(self, w: Tensor) -> Tensor:
82+
G = torch.stack([weight * A for weight, A in zip(w, self.As, strict=False)]).sum(dim=0)
83+
b = torch.stack(
84+
[weight * A @ u for weight, A, u in zip(w, self.As, self.us, strict=False)]
85+
).sum(dim=0)
86+
return torch.linalg.lstsq(G, b, driver="gelsd").solution
87+
88+
@property
89+
def sps_mapping(self) -> "QuadraticForm.SPSMapping":
90+
return self.SPSMapping(self.As, self.us)
91+
92+
93+
class HomogenousQuadraticForm(QuadraticForm):
94+
def __init__(self, A: Tensor, scales: Tensor, us: list[Tensor]) -> None:
95+
self.A = A
96+
self.scales = scales
97+
As = [A * scale for scale in scales]
98+
super().__init__(As=As, us=us)
99+
100+
def __repr__(self) -> str:
101+
return f"{self.__class__.__name__}(A={self.A}, scales={self.scales}, us={self.us})"
102+
103+
104+
class ConvexQuadraticForm(QuadraticForm):
105+
def __init__(self, Bs: list[Tensor], us: list[Tensor]) -> None:
106+
self.Bs = Bs
107+
super().__init__(As=[B @ B.T for B in self.Bs], us=us)
108+
109+
def __repr__(self) -> str:
110+
return f"{self.__class__.__name__}(Bs={self.Bs}, us={self.us})"
111+
112+
113+
class ElementWiseQuadratic(Objective, WithSPSMappingMixin):
114+
def __init__(self, n_dim: int) -> None:
115+
super().__init__(n_params=n_dim, n_values=n_dim)
116+
117+
def __call__(self, x: Tensor) -> Tensor:
118+
if len(x) != self.n_values:
119+
raise ValueError("x must have the same length as the number of values.")
120+
return x**2
121+
122+
def jacobian(self, x: Tensor) -> Tensor:
123+
return torch.diag(torch.stack([2 * x[0], 2 * x[1]]))
124+
125+
class SPSMapping(WithSPSMappingMixin.SPSMapping):
126+
def __init__(self, n_values: int) -> None:
127+
self.n_values = n_values
128+
129+
def __call__(self, w: Tensor) -> Tensor: # noqa: ARG002
130+
return torch.zeros(self.n_values)
131+
132+
@property
133+
def sps_mapping(self) -> "ElementWiseQuadratic.SPSMapping":
134+
return self.SPSMapping(self.n_values)
135+
136+
137+
class Multinorm(Objective, WithSPSMappingMixin):
138+
def __init__(self, a: Tensor) -> None:
139+
n = len(a)
140+
super().__init__(n_params=n, n_values=n)
141+
self.a = a
142+
143+
def __call__(self, x: Tensor) -> Tensor:
144+
if len(x) != self.n_values:
145+
raise ValueError("x must have the same length as the number of values.")
146+
147+
# f_i(x) = a_i * || x - a_i * e_i ||²
148+
return self.a * torch.norm(x.expand(len(x), len(x)) - torch.diag(self.a), dim=1) ** 2
149+
150+
def jacobian(self, x: Tensor) -> Tensor:
151+
return self.a * 2 * (x.expand(len(x), len(x)) - torch.diag(self.a))
152+
153+
class SPSMapping(WithSPSMappingMixin.SPSMapping):
154+
def __init__(self, a: Tensor) -> None:
155+
self.a = a
156+
157+
def __call__(self, w: Tensor) -> Tensor:
158+
return w * self.a
159+
160+
@property
161+
def sps_mapping(self) -> "Multinorm.SPSMapping":
162+
return self.SPSMapping(self.a)

0 commit comments

Comments
 (0)