diff --git a/CHANGELOG.md b/CHANGELOG.md index 9e4764765..d82b8e459 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,13 @@ changelog does not include internal changes that do not affect the user. ## [Unreleased] +### Fixed + +- Fixed `backward` and `mtl_backward` silently broadcasting a single-row Jacobian into a `.jac` + field that already had several rows (e.g. when calling `backward(loss)` after + `backward([loss1, loss2])` without clearing the `.jac` fields). Accumulating a Jacobian with a + different number of rows than the existing `.jac` field now raises a clear `RuntimeError`. + ## [0.18.2] - 2026-11-22 ### Fixed diff --git a/src/torchjd/autojac/_accumulation.py b/src/torchjd/autojac/_accumulation.py index 17763e89b..7cffb9644 100644 --- a/src/torchjd/autojac/_accumulation.py +++ b/src/torchjd/autojac/_accumulation.py @@ -32,6 +32,12 @@ def accumulate_jacs(params: Iterable[Tensor], jacobians: Iterable[Tensor]) -> No ) if is_tensor_with_jac(param): + if param.jac.shape != jac.shape: + raise RuntimeError( + f"attempting to accumulate a jacobian of size '{list(jac.shape)}' into a .jac " + f"field of size '{list(param.jac.shape)}'. Please ensure that the jacobians " + "accumulated into the same tensor have the same number of rows", + ) param.jac = _materialize_if_expanded(param.jac) param.jac += jac else: diff --git a/tests/unit/autojac/_transform/test_accumulate.py b/tests/unit/autojac/_transform/test_accumulate.py index 6e2a137e3..a7f301521 100644 --- a/tests/unit/autojac/_transform/test_accumulate.py +++ b/tests/unit/autojac/_transform/test_accumulate.py @@ -179,6 +179,25 @@ def test_accumulate_jac_fails_when_shape_mismatch() -> None: accumulate(input) +@mark.parametrize(["first_rows", "second_rows"], [(2, 1), (1, 2), (2, 3)]) +def test_accumulate_jac_fails_when_first_dimension_mismatch( + first_rows: int, second_rows: int +) -> None: + """ + Tests that the AccumulateJac transform raises an error when the jacobian to accumulate does not + have the same first dimension as the jacobian already stored in the .jac field. + """ + + key = zeros_([2, 3], requires_grad=True) + accumulate = AccumulateJac() + accumulate({key: ones_([first_rows, 2, 3])}) + + with raises(RuntimeError): + accumulate({key: ones_([second_rows, 2, 3])}) + + assert_jac_close(key, ones_([first_rows, 2, 3])) + + def test_accumulate_jac_check_keys() -> None: """Tests that the `check_keys` method works correctly for AccumulateJac.""" diff --git a/tests/unit/autojac/test_backward.py b/tests/unit/autojac/test_backward.py index 51e42e3ba..2abbbd68e 100644 --- a/tests/unit/autojac/test_backward.py +++ b/tests/unit/autojac/test_backward.py @@ -71,6 +71,22 @@ def test_repeated_calls_with_expanded_jacobian() -> None: assert_jac_close(a, tensor_([[3.0, 3.0]])) +def test_repeated_calls_with_different_number_of_rows() -> None: + """ + Tests that backward raises an error when it would accumulate a Jacobian into a .jac field that + has a different number of rows, instead of broadcasting it. + """ + + a = tensor_([1.0, 2.0], requires_grad=True) + + backward([a.sum(), (a**2).sum()]) + + with raises(RuntimeError): + backward(a.sum()) + + assert_jac_close(a, tensor_([[1.0, 1.0], [2.0, 4.0]])) + + def test_expanded_jacobian_is_not_copied() -> None: """ Tests that backward stores an expanded Jacobian in the .jac field without copying it, and that