Skip to content

Commit f256c81

Browse files
authored
fix(autojac): Materialize expanded jacs and grads (#845)
1 parent 849e672 commit f256c81

4 files changed

Lines changed: 98 additions & 1 deletion

File tree

‎CHANGELOG.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,11 @@ changelog does not include internal changes that do not affect the user.
2323
- Fixed `jac_to_grad` failing with an `AttributeError` (or, with `retain_jac=True`, accumulating
2424
a wrong gradient) when a tensor is repeated in `tensors`. Repeated tensors are now only
2525
considered once.
26+
- Fixed `backward` and `mtl_backward` failing with a `RuntimeError` when the `.jac` or `.grad`
27+
field held an expanded tensor (e.g. when a parameter is directly summed into a loss) and was then
28+
accumulated into by another call, or when such a `.grad` was modified in-place (e.g. with
29+
`clip_grad_norm_`). Expanded gradients are now materialized before being stored in `.grad`, and
30+
an expanded `.jac` is now only materialized when another Jacobian is accumulated into it.
2631

2732
## [0.18.1] - 2026-11-02
2833

‎src/torchjd/autojac/_accumulation.py‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from collections.abc import Iterable
22
from typing import TypeGuard
33

4+
import torch
45
from torch import Tensor
56

67

@@ -31,6 +32,7 @@ def accumulate_jacs(params: Iterable[Tensor], jacobians: Iterable[Tensor]) -> No
3132
)
3233

3334
if is_tensor_with_jac(param):
35+
param.jac = _materialize_if_expanded(param.jac)
3436
param.jac += jac
3537
else:
3638
# We do not clone the value to save memory and time, so subsequent modifications of
@@ -50,7 +52,15 @@ def accumulate_grads(params: Iterable[Tensor], gradients: Iterable[Tensor]) -> N
5052
if hasattr(param, "grad") and param.grad is not None:
5153
param.grad += grad
5254
else:
53-
param.grad = grad
55+
param.grad = _materialize_if_expanded(grad)
56+
57+
58+
def _materialize_if_expanded(tensor: Tensor) -> Tensor:
59+
if tensor.layout == torch.strided and any(
60+
stride == 0 and size > 1 for stride, size in zip(tensor.stride(), tensor.shape, strict=True)
61+
):
62+
return tensor.contiguous()
63+
return tensor
5464

5565

5666
def _check_expects_grad(tensor: Tensor, field_name: str) -> None:

‎tests/unit/autojac/test_backward.py‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
from utils.tensors import eye_, randn_, tensor_
55

66
from torchjd.autojac import backward
7+
from torchjd.autojac._accumulation import is_tensor_with_jac
78
from torchjd.autojac._backward import _create_transform
89
from torchjd.autojac._transform import OrderedSet
910
from torchjd.autojac._utils import create_jac_dict
@@ -55,6 +56,39 @@ def test_jac_is_populated() -> None:
5556
assert_has_jac(a)
5657

5758

59+
def test_repeated_calls_with_expanded_jacobian() -> None:
60+
"""
61+
Tests that backward correctly accumulates the Jacobians across several calls when the Jacobian
62+
of the tensor with respect to the input is an expanded tensor (e.g. because the input is
63+
directly summed).
64+
"""
65+
66+
a = tensor_([1.0, 2.0], requires_grad=True)
67+
68+
backward(a.sum())
69+
backward(2.0 * a.sum())
70+
71+
assert_jac_close(a, tensor_([[3.0, 3.0]]))
72+
73+
74+
def test_expanded_jacobian_is_not_copied() -> None:
75+
"""
76+
Tests that backward stores an expanded Jacobian in the .jac field without copying it, and that
77+
a second call can still accumulate into it.
78+
"""
79+
80+
a = tensor_([1.0, 2.0], requires_grad=True)
81+
82+
backward(a.sum())
83+
84+
assert is_tensor_with_jac(a)
85+
assert 0 in a.jac.stride()
86+
87+
backward(a.sum())
88+
89+
assert_jac_close(a, tensor_([[2.0, 2.0]]))
90+
91+
5892
@mark.parametrize("shape", [(1, 3), (2, 3), (2, 6), (5, 8), (20, 55)])
5993
@mark.parametrize("manually_specify_inputs", [True, False])
6094
@mark.parametrize("chunk_size", [1, 2, None])

‎tests/unit/autojac/test_mtl_backward.py‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
from utils.tensors import arange_, ones_, rand_, randn_, tensor_
1414

1515
from torchjd.autojac import mtl_backward
16+
from torchjd.autojac._accumulation import is_tensor_with_jac
1617
from torchjd.autojac._mtl_backward import _create_grad_tensors_dict, _create_transform
1718
from torchjd.autojac._transform import OrderedSet
1819

@@ -144,6 +145,53 @@ def test_single_task() -> None:
144145
assert_has_grad(p1)
145146

146147

148+
def test_repeated_calls_with_expanded_task_gradient() -> None:
149+
"""
150+
Tests that mtl_backward correctly accumulates the gradients of the task-specific parameters
151+
across several calls when these gradients are expanded tensors (e.g. because the task-specific
152+
parameters are directly summed).
153+
"""
154+
155+
p0 = tensor_([1.0, 2.0], requires_grad=True)
156+
p1 = tensor_([3.0, 4.0], requires_grad=True)
157+
p2 = tensor_([5.0, 6.0], requires_grad=True)
158+
159+
for _ in range(2):
160+
f = tensor_([-1.0, 1.0]) @ p0
161+
y1 = f + p1.sum()
162+
y2 = 2.0 * f + p2.sum()
163+
mtl_backward([y1, y2], features=f)
164+
165+
assert_jac_close(p0, tensor_([[-2.0, 2.0], [-4.0, 4.0]]))
166+
assert_grad_close(p1, tensor_([2.0, 2.0]))
167+
assert_grad_close(p2, tensor_([2.0, 2.0]))
168+
169+
170+
def test_expanded_jac_is_not_copied_but_expanded_grad_is() -> None:
171+
"""
172+
Tests that mtl_backward stores an expanded Jacobian in the .jac field of the shared parameters
173+
without copying it, but materializes an expanded gradient before storing it in the .grad field
174+
of the task-specific parameters. Also tests that a second call accumulates correctly into both.
175+
"""
176+
177+
p0 = tensor_([1.0, 2.0], requires_grad=True)
178+
p1 = tensor_([3.0, 4.0], requires_grad=True)
179+
180+
f = p0.sum()
181+
mtl_backward([f + p1.sum()], features=f)
182+
183+
assert is_tensor_with_jac(p0)
184+
assert 0 in p0.jac.stride()
185+
assert p1.grad is not None
186+
assert 0 not in p1.grad.stride()
187+
188+
f = p0.sum()
189+
mtl_backward([f + p1.sum()], features=f)
190+
191+
assert_jac_close(p0, tensor_([[2.0, 2.0]]))
192+
assert_grad_close(p1, tensor_([2.0, 2.0]))
193+
194+
147195
def test_incoherent_task_number_fails() -> None:
148196
"""
149197
Tests that mtl_backward raises an error when called with the number of tasks losses different

0 commit comments

Comments
 (0)