|
13 | 13 | from utils.tensors import arange_, ones_, rand_, randn_, tensor_ |
14 | 14 |
|
15 | 15 | from torchjd.autojac import mtl_backward |
| 16 | +from torchjd.autojac._accumulation import is_tensor_with_jac |
16 | 17 | from torchjd.autojac._mtl_backward import _create_grad_tensors_dict, _create_transform |
17 | 18 | from torchjd.autojac._transform import OrderedSet |
18 | 19 |
|
@@ -144,6 +145,53 @@ def test_single_task() -> None: |
144 | 145 | assert_has_grad(p1) |
145 | 146 |
|
146 | 147 |
|
| 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 | + |
147 | 195 | def test_incoherent_task_number_fails() -> None: |
148 | 196 | """ |
149 | 197 | Tests that mtl_backward raises an error when called with the number of tasks losses different |
|
0 commit comments