Skip to content

Commit f095b0f

Browse files
authored
feat(aggregation): Add STCH (#719)
Signed-off-by: ppraneth <pranethparuchuri@gmail.com>
1 parent 57974a0 commit f095b0f

6 files changed

Lines changed: 183 additions & 1 deletion

File tree

‎CHANGELOG.md‎

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

1111
### Added
1212

13+
- Added `STCH` from [Smooth Tchebycheff Scalarization for Multi-Objective
14+
Optimization](https://openreview.net/pdf?id=m4dO5L6eCp), a `Scalarizer` that combines the input
15+
tensor of values into a smooth approximation of their (weighted, shifted) maximum.
1316
- 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`.
1417
- Added `GeometricMean` (also known as GLS) studied in [MultiNet++: Multi-Stream Feature
1518
Aggregation and Geometric Loss Strategy for Multi-Task

‎docs/source/docs/scalarization/index.rst‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,4 +19,5 @@ Abstract base class
1919
geometric_mean.rst
2020
mean.rst
2121
random.rst
22+
stch.rst
2223
sum.rst
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
:hide-toc:
2+
3+
STCH
4+
====
5+
6+
.. autoclass:: torchjd.scalarization.STCH
7+
:members: __call__

‎src/torchjd/scalarization/__init__.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
from ._mean import Mean
2525
from ._random import Random
2626
from ._scalarizer_base import Scalarizer
27+
from ._stch import STCH
2728
from ._sum import Sum
2829

29-
__all__ = ["Constant", "GeometricMean", "Mean", "Random", "Scalarizer", "Sum"]
30+
__all__ = ["Constant", "GeometricMean", "Mean", "Random", "Scalarizer", "STCH", "Sum"]

‎src/torchjd/scalarization/_stch.py‎

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
import torch
2+
from torch import Tensor
3+
4+
from ._scalarizer_base import Scalarizer
5+
6+
7+
class STCH(Scalarizer):
8+
r"""
9+
:class:`~torchjd.scalarization.Scalarizer` that combines the input tensor of values using smooth
10+
Tchebycheff scalarization, as defined in `Smooth Tchebycheff Scalarization for Multi-Objective
11+
Optimization <https://openreview.net/pdf?id=m4dO5L6eCp>`_.
12+
13+
It returns
14+
15+
.. math::
16+
\mu \log \sum_{i=1}^m \exp\left(\frac{\lambda_i (f_i - z_i^*)}{\mu}\right),
17+
18+
a smooth approximation of the (non-differentiable) weighted maximum
19+
:math:`\max_i \lambda_i (f_i - z_i^*)` that becomes tighter as ``mu`` decreases.
20+
21+
Following the paper's notation:
22+
23+
- :math:`f_i` is the :math:`i`-th input value (the :math:`i`-th objective),
24+
- :math:`m` is the number of objectives (the number of elements of the input),
25+
- :math:`\lambda_i` is its preference weight (the ``weights`` parameter),
26+
- :math:`z_i^*` is the :math:`i`-th component of the ideal point (the ``reference`` parameter),
27+
- :math:`\mu` is the smoothing parameter (the ``mu`` parameter).
28+
29+
:param mu: The smoothing parameter :math:`\mu`. Must be strictly positive. Smaller values make
30+
the scalarization closer to the maximum. The paper evaluates :math:`\mu \in \{0.01, 0.1,
31+
0.5, 1\}` and reports that a small :math:`\mu` works reasonably well, while no single value
32+
is best across all problems.
33+
:param weights: The preference vector :math:`\lambda` applied to the values (in the paper, on
34+
the probability simplex). If ``None``, a uniform preference summing to one is used. If
35+
provided, it must have the same shape as the values passed at call time.
36+
:param reference: The ideal point :math:`z^*` subtracted from the values. If ``None``, no shift
37+
is applied. If provided, it must have the same shape as the values passed at call time.
38+
"""
39+
40+
def __init__(
41+
self,
42+
mu: float,
43+
weights: Tensor | None = None,
44+
reference: Tensor | None = None,
45+
) -> None:
46+
if mu <= 0.0:
47+
raise ValueError(f"Parameter `mu` should be strictly positive. Found `mu = {mu}`.")
48+
49+
super().__init__()
50+
self.mu = mu
51+
self.weights = weights
52+
self.reference = reference
53+
54+
def forward(self, values: Tensor, /) -> Tensor:
55+
if self.weights is not None and self.weights.shape != values.shape:
56+
raise ValueError(
57+
f"Parameter `weights` should have the same shape as `values`. Found "
58+
f"`weights.shape = {tuple(self.weights.shape)}` and `values.shape = "
59+
f"{tuple(values.shape)}`."
60+
)
61+
if self.reference is not None and self.reference.shape != values.shape:
62+
raise ValueError(
63+
f"Parameter `reference` should have the same shape as `values`. Found "
64+
f"`reference.shape = {tuple(self.reference.shape)}` and `values.shape = "
65+
f"{tuple(values.shape)}`."
66+
)
67+
68+
if self.weights is None:
69+
weights = torch.full_like(values, 1.0 / values.numel())
70+
else:
71+
weights = self.weights
72+
73+
shifted = values if self.reference is None else values - self.reference
74+
75+
# Center the weighted values before dividing by mu (Appendix B.1 of the paper). This keeps
76+
# the largest exponent at 0 so the `/ mu` step never overflows for large values and small
77+
# mu. Adding `max_y` back makes it value-preserving: the result and its gradient are
78+
# mathematically identical to `mu * logsumexp(weights * shifted / mu)`.
79+
y = weights * shifted
80+
max_y = y.max()
81+
exponents = (y - max_y) / self.mu
82+
return self.mu * torch.logsumexp(exponents.flatten(), dim=-1) + max_y
83+
84+
def __repr__(self) -> str:
85+
return (
86+
f"{self.__class__.__name__}(mu={self.mu}, weights={self.weights!r}, "
87+
f"reference={self.reference!r})"
88+
)
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
import torch
2+
from pytest import mark, raises
3+
from torch import Tensor
4+
from utils.tensors import tensor_
5+
6+
from torchjd.scalarization import STCH
7+
8+
from ._asserts import (
9+
assert_grad_flow,
10+
assert_permutation_invariant,
11+
assert_returns_scalar,
12+
)
13+
from ._inputs import all_inputs
14+
15+
16+
def test_value_default() -> None:
17+
# Uniform weights, no reference: mu * logsumexp([0, 0]) = log(2).
18+
out = STCH(mu=1.0)(tensor_([0.0, 0.0]))
19+
torch.testing.assert_close(out, torch.log(tensor_(2.0)))
20+
21+
22+
def test_value_with_weights() -> None:
23+
# weights = [1, 1] on values [1, 1]: mu * logsumexp([1, 1]) = 1 + log(2).
24+
out = STCH(mu=1.0, weights=tensor_([1.0, 1.0]))(tensor_([1.0, 1.0]))
25+
torch.testing.assert_close(out, 1.0 + torch.log(tensor_(2.0)))
26+
27+
28+
def test_value_with_reference() -> None:
29+
# reference shifts values to [0, 0], so the result collapses back to log(2).
30+
out = STCH(mu=1.0, weights=tensor_([1.0, 1.0]), reference=tensor_([1.0, 1.0]))(
31+
tensor_([1.0, 1.0])
32+
)
33+
torch.testing.assert_close(out, torch.log(tensor_(2.0)))
34+
35+
36+
@mark.parametrize("losses", all_inputs)
37+
def test_expected_structure(losses: Tensor) -> None:
38+
assert_returns_scalar(STCH(mu=1.0), losses)
39+
40+
41+
@mark.parametrize("losses", all_inputs)
42+
def test_grad_flow(losses: Tensor) -> None:
43+
assert_grad_flow(STCH(mu=1.0), losses)
44+
45+
46+
@mark.parametrize("losses", all_inputs)
47+
def test_permutation_invariant(losses: Tensor) -> None:
48+
# With uniform weights and no reference, STCH is symmetric in its inputs.
49+
assert_permutation_invariant(STCH(mu=1.0), losses)
50+
51+
52+
def test_does_not_overflow_for_large_values_and_small_mu() -> None:
53+
# `weights * values / mu` would overflow to inf before logsumexp can stabilize it. The
54+
# value-preserving centering keeps the result finite and equal to the dominant (max) term.
55+
values = tensor_([1e30, 2e30, 3e30])
56+
out = STCH(mu=1e-10)(values)
57+
assert out.isfinite()
58+
torch.testing.assert_close(out, tensor_(1e30)) # 3e30 weighted by the uniform 1/3.
59+
60+
61+
@mark.parametrize("mu", [0.0, -1.0])
62+
def test_raises_on_non_positive_mu(mu: float) -> None:
63+
with raises(ValueError):
64+
STCH(mu=mu)
65+
66+
67+
def test_raises_on_weights_shape_mismatch() -> None:
68+
scalarizer = STCH(mu=1.0, weights=tensor_([1.0, 1.0, 1.0]))
69+
with raises(ValueError):
70+
scalarizer(tensor_([1.0, 1.0]))
71+
72+
73+
def test_raises_on_reference_shape_mismatch() -> None:
74+
scalarizer = STCH(mu=1.0, reference=tensor_([1.0, 1.0, 1.0]))
75+
with raises(ValueError):
76+
scalarizer(tensor_([1.0, 1.0]))
77+
78+
79+
def test_representations() -> None:
80+
s = STCH(mu=0.5)
81+
assert repr(s) == "STCH(mu=0.5, weights=None, reference=None)"
82+
assert str(s) == "STCH"

0 commit comments

Comments
 (0)