Skip to content

Commit dbfe8f7

Browse files
authored
fix(aggregation): Fix in GeometricMean (#718)
Signed-off-by: ppraneth <pranethparuchuri@gmail.com>
1 parent 47ad975 commit dbfe8f7

2 files changed

Lines changed: 19 additions & 8 deletions

File tree

‎src/torchjd/scalarization/_geometric_mean.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,9 @@ class GeometricMean(Scalarizer):
1515
"""
1616

1717
def forward(self, values: Tensor, /) -> Tensor:
18-
if (values < 1e-12).any():
18+
if (values < 0.0).any():
1919
raise ValueError(
20-
"GeometricMean is only defined for strictly positive values. Found a value "
21-
"below 1e-12 in the input."
20+
"GeometricMean is only defined for strictly positive values."
21+
"Found a negative value in the input."
2222
)
2323
return torch.exp(torch.log(values).mean())

‎tests/unit/scalarization/test_geometric_mean.py‎

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -36,16 +36,27 @@ def test_permutation_invariant(losses: Tensor) -> None:
3636

3737

3838
@mark.parametrize(
39-
"invalid",
39+
"negative",
4040
[
41-
tensor_([1.0, 0.0]),
4241
tensor_([1.0, -1.0]),
43-
tensor_([1.0, 1e-13]),
42+
tensor_([-1e-13, 2.0]),
43+
tensor_([-1.0]),
4444
],
4545
)
46-
def test_raises_on_non_positive_input(invalid: Tensor) -> None:
46+
def test_raises_on_negative_input(negative: Tensor) -> None:
4747
with raises(ValueError):
48-
GeometricMean()(invalid)
48+
GeometricMean()(negative)
49+
50+
51+
def test_returns_zero_when_a_value_is_zero() -> None:
52+
# log(0) = -inf, so the geometric mean collapses to 0. This matches the LibMTL behavior;
53+
# the gradient is nan, which is expected for this method.
54+
assert GeometricMean()(tensor_([1.0, 0.0])) == 0.0
55+
56+
57+
def test_does_not_raise_on_tiny_positive_input() -> None:
58+
# Tiny but strictly positive values are valid and must not be rejected.
59+
assert GeometricMean()(tensor_([1.0, 1e-13])).isfinite()
4960

5061

5162
def test_representations() -> None:

0 commit comments

Comments
 (0)