Skip to content

Commit 57aacaf

Browse files
committed
test: Add Valley-Bowl, optimizer and LR options to trajectories
Add the Valley-Bowl toy problem from CAGrad and Nash-MTL as the VB and VB01 objectives, and add --optimizer and --lr flags to optimize.py.
1 parent 4a66f67 commit 57aacaf

6 files changed

Lines changed: 172 additions & 9 deletions

File tree

‎tests/trajectories/_constants.py‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
from torchjd.aggregation import (
55
IMTLG,
66
MGDA,
7+
Aggregator,
78
AlignedMTL,
89
CAGrad,
910
DualProj,
@@ -18,9 +19,10 @@
1819
ElementWiseQuadratic,
1920
HomogenousQuadraticFunction,
2021
QuadraticFunction,
22+
ValleyBowl,
2123
)
2224

23-
AGGREGATORS = {
25+
AGGREGATORS: dict[str, Aggregator] = {
2426
"upgrad": UPGrad(projector=QuadprogProjector(reg_eps=1e-7, norm_eps=1e-9)),
2527
"mgda": MGDA(),
2628
"cagrad": CAGrad(c=0.5),
@@ -33,6 +35,10 @@
3335
"random": Random(),
3436
"mean": Mean(),
3537
}
38+
OPTIMIZERS: dict[str, type[torch.optim.SGD] | type[torch.optim.Adam]] = {
39+
"sgd": torch.optim.SGD,
40+
"adam": torch.optim.Adam,
41+
}
3642
LR_MULTIPLIERS = {
3743
"upgrad": 1.0,
3844
"mgda": 2.0,
@@ -91,6 +97,8 @@
9197
}
9298

9399
OBJECTIVES = {
100+
"VB": ValleyBowl(),
101+
"VB01": ValleyBowl(scale=0.1),
94102
"EWQ": ElementWiseQuadratic(2),
95103
"CQF": QuadraticFunction(
96104
As=[torch.tensor([[1.0, 0.2], [0.2, 0.05]]), torch.tensor([[3.0, -0.6], [-0.6, 0.2]])],
@@ -103,11 +111,16 @@
103111
),
104112
}
105113
BASE_LEARNING_RATES = {
114+
"VB": 0.001,
115+
"VB01": 0.001,
106116
"EWQ": 0.075,
107117
"CQF": 0.125,
108118
"HQF": 0.005,
109119
}
120+
_VB_INITIAL_POINTS = [[-8.5, 7.5], [0.0, 0.0], [9.0, 9.0], [-7.5, -0.5], [9.0, -1.0]]
110121
INITIAL_POINTS = {
122+
"VB": _VB_INITIAL_POINTS,
123+
"VB01": _VB_INITIAL_POINTS,
111124
"EWQ": [
112125
[3.0, -2.0],
113126
[0.0, -3.0],
@@ -128,6 +141,8 @@
128141
],
129142
}
130143
N_ITERS = {
144+
"VB": 35000,
145+
"VB01": 35000,
131146
"EWQ": 50,
132147
"CQF": 200,
133148
"HQF": 100,

‎tests/trajectories/_objectives.py‎

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from __future__ import annotations
22

33
from abc import ABC, abstractmethod
4+
from typing import cast
45

56
import torch
67
from torch import Tensor
@@ -130,3 +131,67 @@ def __init__(self, n_values: int) -> None:
130131

131132
def __call__(self, w: Tensor) -> Tensor: # noqa: ARG002
132133
return torch.zeros(self.n_values)
134+
135+
136+
class ValleyBowl(Objective):
137+
"""Two-objective toy problem from CAGrad (Liu et al., 2021), also used by Nash-MTL
138+
(Navon et al., 2022).
139+
140+
Above :math:`x_2 = 0`, each objective is a log-shaped valley; below it, a quadratic bowl.
141+
142+
Reference implementations:
143+
144+
- CAGrad: https://github.com/Cranial-XIX/CAGrad/blob/main/toy.py
145+
- Nash-MTL: https://github.com/AvivNavon/nash-mtl/tree/main/experiments/toy
146+
147+
:param scale: Multiplier for the first objective.
148+
:param scale_both_losses: Multiplier applied to both objectives.
149+
"""
150+
151+
# Value used for the Pareto set in CAGrad's plotting code (``toy.py``, ``plot_contour``).
152+
PARETO_SET_X2 = -8.3552
153+
154+
def __init__(self, scale: float = 1.0, scale_both_losses: float = 1.0) -> None:
155+
super().__init__(n_params=2, n_values=2)
156+
self.scale = scale
157+
self.scale_both_losses = scale_both_losses
158+
159+
def __call__(self, x: Tensor) -> Tensor:
160+
if x.shape != (2,):
161+
raise ValueError("x must have shape (2,).")
162+
x1, x2 = x.unbind()
163+
valley1 = (0.5 * (-x1 - 7) - torch.tanh(-x2)).abs().clamp_min(5e-6).log() + 6
164+
valley2 = (0.5 * (-x1 + 3) + torch.tanh(-x2) + 2).abs().clamp_min(5e-6).log() + 6
165+
above = torch.tanh(x2 * 0.5).clamp_min(0)
166+
below = torch.tanh(-x2 * 0.5).clamp_min(0)
167+
bowl1 = ((-x1 + 7).square() + 0.1 * (-x2 - 8).square()) / 10 - 20
168+
bowl2 = ((-x1 - 7).square() + 0.1 * (-x2 - 8).square()) / 10 - 20
169+
return (
170+
torch.stack(
171+
((valley1 * above + bowl1 * below) * self.scale, valley2 * above + bowl2 * below)
172+
)
173+
* self.scale_both_losses
174+
)
175+
176+
def jacobian(self, x: Tensor) -> Tensor:
177+
return cast(Tensor, torch.func.jacrev(self)(x))
178+
179+
def __repr__(self) -> str:
180+
return f"ValleyBowl(scale={self.scale}, scale_both_losses={self.scale_both_losses})"
181+
182+
def pareto_set(self, n: int = 1000) -> Tensor:
183+
"""Sample the reference Pareto set used by the Valley-Bowl example.
184+
185+
:param n: Number of points to sample along the reference set.
186+
"""
187+
return torch.stack(
188+
(torch.linspace(-7.0, 7.0, n), torch.full((n,), self.PARETO_SET_X2)), dim=1
189+
)
190+
191+
@property
192+
def optimum(self) -> Tensor:
193+
"""
194+
Pareto-optimal point that (approximately) minimizes the mean of the unscaled objectives. It
195+
does not depend on ``scale`` or ``scale_both_losses``.
196+
"""
197+
return torch.tensor([0.0, self.PARETO_SET_X2])

‎tests/trajectories/_optimization.py‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,21 @@ def optimize(
1414
aggregator: Aggregator,
1515
lr: float,
1616
n_iters: int,
17+
optimizer_cls: type[torch.optim.SGD] | type[torch.optim.Adam] = torch.optim.SGD,
1718
) -> tuple[list[Tensor], list[Tensor]]:
19+
"""Run an aggregator with the selected PyTorch optimizer.
20+
21+
:param objective: Vector-valued objective to optimize.
22+
:param initial_x: Starting point in parameter space.
23+
:param aggregator: Aggregator applied to the objective Jacobian.
24+
:param lr: Optimizer learning rate.
25+
:param n_iters: Number of optimization steps.
26+
:param optimizer_cls: Optimizer class to instantiate for this trajectory.
27+
"""
1828
xs = []
1929
ys = []
2030
x = initial_x.clone().requires_grad_()
21-
optimizer = torch.optim.SGD([x], lr=lr)
31+
optimizer = optimizer_cls([x], lr=lr)
2232
for i in range(n_iters):
2333
print(f"{i + 1}/{n_iters}", end="\r")
2434
xs.append(x.detach().clone())

‎tests/trajectories/optimize.py‎

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
spaces.
44
55
Usage:
6-
uv run python tests/trajectories/optimize.py <objective> <aggregator>...
6+
uv run python tests/trajectories/optimize.py <objective> <aggregator>... [--optimizer sgd|adam] [--lr LR]
77
88
Arguments:
99
<objective> The key of the objective function (e.g., EWQ, CQF, HQF).
@@ -28,6 +28,7 @@
2828
LR_MULTIPLIERS,
2929
N_ITERS,
3030
OBJECTIVES,
31+
OPTIMIZERS,
3132
)
3233
from trajectories._optimization import optimize
3334
from trajectories._paths import get_params_dir, get_values_dir
@@ -52,7 +53,19 @@ def main() -> None:
5253
metavar="aggregator",
5354
help=f"Keys of the aggregators to use. Choices: {list(AGGREGATORS)}",
5455
)
56+
parser.add_argument(
57+
"--optimizer",
58+
"--optim",
59+
choices=list(OPTIMIZERS),
60+
default="sgd",
61+
help="Optimizer (default: sgd).",
62+
)
63+
parser.add_argument(
64+
"--lr", type=float, default=None, help="Use this learning rate for every aggregator."
65+
)
5566
args = parser.parse_args()
67+
if args.lr is not None and (not np.isfinite(args.lr) or args.lr <= 0):
68+
parser.error("--lr must be finite and positive")
5669

5770
objective_key = args.objective
5871
if objective_key not in OBJECTIVES:
@@ -71,8 +84,9 @@ def main() -> None:
7184
base_lr = BASE_LEARNING_RATES[objective_key]
7285
for key in LR_MULTIPLIERS:
7386
mult = lr_multiplier_overrides.get(key, LR_MULTIPLIERS[key])
74-
learning_rates[key] = mult * base_lr
87+
learning_rates[key] = args.lr if args.lr is not None else mult * base_lr
7588
n_iters = N_ITERS[objective_key]
89+
optimizer_cls = OPTIMIZERS[args.optimizer]
7690

7791
torch.use_deterministic_algorithms(True)
7892

@@ -88,6 +102,7 @@ def main() -> None:
88102
"aggregator_reprs": {key: repr(AGGREGATORS[key]) for key in aggregator_keys},
89103
"learning_rates": learning_rates,
90104
"initial_points": initial_points,
105+
"optimizer": args.optimizer,
91106
}
92107
with open(TRAJECTORIES_RESULTS_DIR / objective_key / "metadata.json", "w") as f:
93108
json.dump(metadata, f)
@@ -107,7 +122,12 @@ def main() -> None:
107122

108123
initial_x = torch.tensor(initial_point)
109124
xs, ys = optimize(
110-
objective, initial_x=initial_x, aggregator=aggregator, lr=lr, n_iters=n_iters
125+
objective,
126+
initial_x=initial_x,
127+
aggregator=aggregator,
128+
lr=lr,
129+
n_iters=n_iters,
130+
optimizer_cls=optimizer_cls,
111131
)
112132

113133
xs_list.append(torch.stack(xs))

‎tests/trajectories/plot_params.py‎

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313

1414
import matplotlib.pyplot as plt
1515
import numpy as np
16+
import torch
1617

1718
from tests.paths import TRAJECTORIES_RESULTS_DIR
1819
from trajectories._constants import (
@@ -22,7 +23,7 @@
2223
LATEX_NAMES,
2324
OBJECTIVES,
2425
)
25-
from trajectories._objectives import ElementWiseQuadratic, WithSPSMappingMixin
26+
from trajectories._objectives import ElementWiseQuadratic, ValleyBowl, WithSPSMappingMixin
2627
from trajectories._optimization import compute_gradient_cosine_similarities
2728
from trajectories._pareto_utils import sample_2d_spss
2829
from trajectories._paths import get_param_plots_dir, get_params_dir
@@ -84,6 +85,11 @@ def main() -> None:
8485

8586
common_plotter = SquareBoxAspectSetter()
8687

88+
if isinstance(objective, ValleyBowl):
89+
sps_points = objective.pareto_set().numpy()
90+
main_content = np.concatenate([main_content, sps_points])
91+
common_plotter += SPSPlotter(sps_points)
92+
8793
if objective.n_values == 2 and isinstance(objective, WithSPSMappingMixin):
8894
sps_points = sample_2d_spss(objective).numpy()
8995
main_content = np.concatenate([main_content, sps_points])
@@ -97,7 +103,22 @@ def main() -> None:
97103
adjust_plotter = ContentLimAdjuster(main_content)
98104
common_plotter += adjust_plotter
99105

100-
if objective.n_values == 2:
106+
if isinstance(objective, ValleyBowl):
107+
x0 = torch.linspace(adjust_plotter.xlim[0], adjust_plotter.xlim[1], 200)
108+
x1 = torch.linspace(adjust_plotter.ylim[0], adjust_plotter.ylim[1], 200)
109+
grid = torch.cartesian_prod(x0, x1)
110+
mean_loss = torch.vmap(objective)(grid).mean(dim=1).reshape(200, 200)
111+
common_plotter += HeatmapPlotter(
112+
values=mean_loss.numpy(),
113+
x_min=adjust_plotter.xlim[0],
114+
x_max=adjust_plotter.xlim[1],
115+
y_min=adjust_plotter.ylim[0],
116+
y_max=adjust_plotter.ylim[1],
117+
vmin=float(mean_loss.min()),
118+
vmax=float(mean_loss.max()),
119+
cmap="viridis",
120+
)
121+
elif objective.n_values == 2:
101122
similarities = compute_gradient_cosine_similarities(
102123
objective,
103124
x0_min=adjust_plotter.xlim[0],
@@ -147,6 +168,10 @@ def main() -> None:
147168
plotter += YAxisLabeller("$x_2$") if j == 0 else YTicksClearer()
148169

149170
plotter(axes[i][j])
171+
if isinstance(objective, ValleyBowl):
172+
axes[i][j].scatter(
173+
*objective.optimum.tolist(), marker="*", color="black", s=45, zorder=10
174+
)
150175

151176
fig.tight_layout(h_pad=-2.5)
152177
print("Saving figure")

‎tests/trajectories/plot_values.py‎

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313

1414
import matplotlib.pyplot as plt
1515
import numpy as np
16+
import torch
1617

1718
from tests.paths import TRAJECTORIES_RESULTS_DIR
1819
from trajectories._constants import (
@@ -22,7 +23,7 @@
2223
OBJECTIVES,
2324
PLOT_VALUES_LIMS,
2425
)
25-
from trajectories._objectives import WithSPSMappingMixin
26+
from trajectories._objectives import ValleyBowl, WithSPSMappingMixin
2627
from trajectories._pareto_utils import compute_normalized_2d_pf_distances, sample_2d_pf
2728
from trajectories._paths import get_value_plots_dir, get_values_dir
2829
from trajectories._plotters import (
@@ -82,6 +83,12 @@ def main() -> None:
8283
initial_values = first_agg_Y[:, 0, :]
8384
main_content = initial_values
8485

86+
if isinstance(objective, ValleyBowl):
87+
front = torch.vmap(objective)(objective.pareto_set())
88+
pf_points_array = front.numpy()
89+
common_plotter += PFPlotter(pf_points_array)
90+
main_content = np.concatenate([main_content, pf_points_array])
91+
8592
if isinstance(objective, WithSPSMappingMixin):
8693
pf_points_array = sample_2d_pf(objective).numpy()
8794
common_plotter += PFPlotter(pf_points_array)
@@ -98,7 +105,25 @@ def main() -> None:
98105
xlim = adjust_plotter.xlim
99106
ylim = adjust_plotter.ylim
100107

101-
if isinstance(objective, WithSPSMappingMixin):
108+
if isinstance(objective, ValleyBowl):
109+
grid = torch.cartesian_prod(
110+
torch.linspace(xlim[0], xlim[1], 200), torch.linspace(ylim[0], ylim[1], 200)
111+
)
112+
distances = torch.cat(
113+
[torch.cdist(chunk, front).min(dim=1).values for chunk in grid.split(512)]
114+
)
115+
distances = distances.reshape(200, 200)
116+
common_plotter += HeatmapPlotter(
117+
values=distances.numpy(),
118+
x_min=xlim[0],
119+
x_max=xlim[1],
120+
y_min=ylim[0],
121+
y_max=ylim[1],
122+
vmin=0,
123+
vmax=float(distances.max()),
124+
cmap="magma_r",
125+
)
126+
elif isinstance(objective, WithSPSMappingMixin):
102127
distances = compute_normalized_2d_pf_distances(
103128
objective,
104129
y0_min=xlim[0],
@@ -145,6 +170,9 @@ def main() -> None:
145170
plotter += YAxisLabeller("Objective $2$") if j == 0 else YTicksClearer()
146171

147172
plotter(axes[i][j])
173+
if isinstance(objective, ValleyBowl):
174+
optimum = objective(objective.optimum).numpy()
175+
axes[i][j].scatter(*optimum, marker="*", color="black", s=45, zorder=10)
148176

149177
fig.tight_layout(h_pad=-2.5)
150178
print("Saving figure")

0 commit comments

Comments
 (0)