Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 6 additions & 0 deletions src/torchjd/autojac/_accumulation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
19 changes: 19 additions & 0 deletions tests/unit/autojac/_transform/test_accumulate.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""

Expand Down
16 changes: 16 additions & 0 deletions tests/unit/autojac/test_backward.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading