Skip to content

Commit 120272a

Browse files
authored
fix(autogram): Raise error on forward pass without backward pass (#793)
1 parent e142058 commit 120272a

4 files changed

Lines changed: 38 additions & 1 deletion

File tree

‎CHANGELOG.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,9 @@ changelog does not include internal changes that do not affect the user.
1818
matrix are almost equal. Rounding errors could make the squared distance between such rows
1919
slightly negative, giving a `nan` distance that was then ignored when computing the scores.
2020
Squared distances are now clamped to be non-negative before taking the square root.
21+
- Fixed `Engine.compute_gramian` silently ignoring the contribution of a module when one of its
22+
forward passes had no associated backward pass (e.g. because its output was detached). It now
23+
raises a `ValueError` instead.
2124

2225
## [0.17.1] - 2026-09-23
2326

‎src/torchjd/autogram/_engine.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -326,6 +326,12 @@ def differentiation(_grad_output: Tensor) -> tuple[Tensor, ...]:
326326
grad_output = torch.ones_like(output)
327327
_ = differentiation(grad_output)
328328

329+
if any(computer.has_pending_jacobian() for computer in self._gramian_computers.values()):
330+
raise ValueError(
331+
"Some modules had a forward pass without an associated backward pass (e.g. because "
332+
"its output was detached)."
333+
)
334+
329335
# If the gramian were None, then leaf_targets would be empty, so autograd.grad would
330336
# have failed. So gramian is necessarily a valid Tensor here.
331337
gramian = cast(PSDMatrix, self._gramian_accumulator.gramian)

‎src/torchjd/autogram/_gramian_computer.py‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,12 @@ def track_forward_call(self) -> None:
2828
def reset(self) -> None:
2929
"""Reset state if any. Necessary in some implementations."""
3030

31+
@abstractmethod
32+
def has_pending_jacobian(self) -> bool:
33+
"""
34+
Whether some Jacobian was computed but its Gramian was never returned. Necessary in some implementations.
35+
"""
36+
3137

3238
class JacobianBasedGramianComputer(GramianComputer, ABC):
3339
def __init__(self, jacobian_computer: JacobianComputer) -> None:
@@ -52,6 +58,9 @@ def reset(self) -> None:
5258
def track_forward_call(self) -> None:
5359
self.remaining_counter += 1
5460

61+
def has_pending_jacobian(self) -> bool:
62+
return self.summed_jacobian is not None
63+
5564
def __call__(
5665
self,
5766
rg_outputs: tuple[Tensor, ...],
@@ -72,6 +81,6 @@ def __call__(
7281

7382
if self.remaining_counter == 0:
7483
gramian = compute_gramian(self.summed_jacobian)
75-
del self.summed_jacobian
84+
self.summed_jacobian = None
7685
return gramian
7786
return None

‎tests/unit/autogram/test_engine.py‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -570,3 +570,22 @@ def test_batched_non_batched_equivalence_2(factory: ModuleFactory, batch_size: i
570570
gramian_none = engine_none.compute_gramian(losses_none)
571571

572572
assert_close(gramian_0, gramian_none, rtol=1e-4, atol=1e-5)
573+
574+
575+
@mark.parametrize("batch_dim", [0, None])
576+
def test_forward_pass_without_backward_pass_raises(batch_dim: int | None) -> None:
577+
"""
578+
Tests that compute_gramian raises an error when a module has a forward pass without an
579+
associated backward pass, instead of silently ignoring the contribution of this module.
580+
"""
581+
582+
encoder = ModuleFactory(Linear, 3, 3)()
583+
head = ModuleFactory(Linear, 3, 1)()
584+
engine = Engine(encoder, head, batch_dim=batch_dim)
585+
input = randn_((4, 3))
586+
587+
target = encoder(input + 0.1).detach() # No backward pass will go through this forward pass
588+
losses = (head(encoder(input)) - target.sum(dim=1, keepdim=True)).squeeze(dim=1) ** 2
589+
590+
with pytest.raises(ValueError):
591+
engine.compute_gramian(losses)

0 commit comments

Comments
 (0)