Skip to content

Commit 06349de

Browse files
authored
fix(autojac): Handle repeated tensors in jac_to_grad (#844)
1 parent 4a66f67 commit 06349de

3 files changed

Lines changed: 31 additions & 2 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,9 @@ changelog does not include internal changes that do not affect the user.
2020
`initial_weights` and `leak`). These tensors are now registered as non-persistent buffers, so
2121
they follow the dtype and device of the aggregator or weighting without being added to its
2222
`state_dict`.
23+
- Fixed `jac_to_grad` failing with an `AttributeError` (or, with `retain_jac=True`, accumulating
24+
a wrong gradient) when a tensor is repeated in `tensors`. Repeated tensors are now only
25+
considered once.
2326

2427
## [0.18.1] - 2026-11-02
2528

‎src/torchjd/autojac/_jac_to_grad.py‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
from torchjd.linalg import Matrix, PSDMatrix
1616

1717
from ._accumulation import TensorWithJac, accumulate_grads, is_tensor_with_jac
18+
from ._transform import OrderedSet
1819
from ._utils import check_consistent_first_dimension
1920

2021

@@ -62,7 +63,8 @@ def jac_to_grad(
6263
into their ``.grad`` fields.
6364
6465
:param tensors: The tensors whose ``.jac`` fields should be aggregated. All Jacobians must
65-
have the same first dimension (e.g. number of losses).
66+
have the same first dimension (e.g. number of losses). Repeated tensors are only considered
67+
once.
6668
:param aggregator: The aggregator used to reduce the Jacobians into gradients. If it uses a
6769
:class:`~torchjd.aggregation.Weighting` to combine the rows of the Jacobians,
6870
``jac_to_grad`` will also return the computed weights.
@@ -118,7 +120,7 @@ def jac_to_grad(
118120
"""
119121

120122
tensors_ = list[TensorWithJac]()
121-
for t in tensors:
123+
for t in OrderedSet(tensors):
122124
if not is_tensor_with_jac(t):
123125
raise ValueError(
124126
"Some `jac` fields were not populated. Did you use `autojac.backward` or "

‎tests/unit/autojac/test_jac_to_grad.py‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,30 @@ def test_single_tensor() -> None:
9191
assert_grad_close(t, g)
9292

9393

94+
@mark.parametrize("retain_jac", [True, False])
95+
@mark.parametrize("optimize", [True, False])
96+
def test_repeated_tensors(retain_jac: bool, optimize: bool) -> None:
97+
"""Tests that jac_to_grad considers repeated tensors only once."""
98+
99+
aggregator = base_agg()
100+
t1 = tensor_(1.0, requires_grad=True)
101+
t2 = tensor_([2.0, 3.0], requires_grad=True)
102+
jac = tensor_([[-4.0, 1.0, 1.0], [6.0, 1.0, 1.0]])
103+
t1.__setattr__("jac", jac[:, 0])
104+
t2.__setattr__("jac", jac[:, 1:])
105+
g = aggregator(jac)
106+
107+
jac_to_grad(
108+
[t1, t2, t1],
109+
aggregator,
110+
retain_jac=retain_jac,
111+
optimize_gramian_computation=optimize,
112+
)
113+
114+
assert_grad_close(t1, g[0])
115+
assert_grad_close(t2, g[1:])
116+
117+
94118
def test_no_jac_field() -> None:
95119
"""Tests that jac_to_grad fails when a tensor does not have a jac field."""
96120

0 commit comments

Comments
 (0)