Skip to content
Merged
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
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@ changelog does not include internal changes that do not affect the user.

## [Unreleased]

### Fixed

- Fixed overflow and precision loss when computing Gramians from mixed-dtype Jacobians in
`autogram.Engine.compute_gramian` and `autojac.jac_to_grad` with
`optimize_gramian_computation=True`. Each partial Gramian is computed in the promoted dtype.

## [0.18.2] - 2026-11-22

### Fixed
Expand Down
11 changes: 11 additions & 0 deletions src/torchjd/autogram/_engine.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from functools import reduce
from typing import cast

import torch
Expand Down Expand Up @@ -287,6 +288,16 @@ def compute_gramian(self, output: Tensor, /) -> Tensor:
self._module_hook_manager.gramian_accumulation_phase.value = True

try:
# Match the dtype of the concatenated Jacobian before forming any partial Gramian.
dtypes = {
param.dtype
for module in self._gramian_computers
for param in module.parameters()
if param.requires_grad
}
self._gramian_accumulator.dtype = (
reduce(torch.promote_types, dtypes) if dtypes else None
)
square_gramian = self._compute_square_gramian(reshaped_output, has_non_batch_dim)
finally:
# Reset everything that has a state, even if the previous call raised an exception
Expand Down
4 changes: 4 additions & 0 deletions src/torchjd/autogram/_gramian_accumulator.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from torch import dtype

from torchjd.linalg import PSDMatrix


Expand All @@ -11,9 +13,11 @@ class GramianAccumulator:
"""

def __init__(self) -> None:
self.dtype: dtype | None = None
self._gramian: PSDMatrix | None = None

def reset(self) -> None:
self.dtype = None
self._gramian = None

def accumulate_gramian(self, gramian: PSDMatrix) -> None:
Expand Down
6 changes: 4 additions & 2 deletions src/torchjd/autogram/_gramian_computer.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from abc import ABC, abstractmethod
from typing import cast

from torch import Tensor
from torch import Tensor, dtype
from torch.utils._pytree import PyTree

from torchjd._linalg import compute_gramian
Expand All @@ -17,6 +17,7 @@ def __call__(
grad_outputs: tuple[Tensor, ...],
args: tuple[PyTree, ...],
kwargs: dict[str, PyTree],
jacobian_dtype: dtype | None,
) -> PSDMatrix | None:
"""Compute what we can for a module and optionally return the gramian if it's ready."""

Expand Down Expand Up @@ -67,6 +68,7 @@ def __call__(
grad_outputs: tuple[Tensor, ...],
args: tuple[PyTree, ...],
kwargs: dict[str, PyTree],
jacobian_dtype: dtype | None,
) -> PSDMatrix | None:
"""Compute what we can for a module and optionally return the gramian if it's ready."""

Expand All @@ -80,7 +82,7 @@ def __call__(
self.remaining_counter -= 1

if self.remaining_counter == 0:
gramian = compute_gramian(self.summed_jacobian)
gramian = compute_gramian(self.summed_jacobian.to(dtype=jacobian_dtype))
self.summed_jacobian = None
return gramian
return None
1 change: 1 addition & 0 deletions src/torchjd/autogram/_module_hook_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,7 @@ def backward(ctx: Any, *grad_outputs: Tensor) -> tuple:
grad_outputs,
ctx.args,
ctx.kwargs,
ctx.gramian_accumulator.dtype,
)
if optional_gramian is not None:
ctx.gramian_accumulator.accumulate_gramian(optional_gramian)
Expand Down
4 changes: 3 additions & 1 deletion src/torchjd/autojac/_jac_to_grad.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from collections import deque
from collections.abc import Iterable
from functools import reduce
from typing import TypeGuard, cast, overload

import torch
Expand Down Expand Up @@ -213,7 +214,8 @@ def _gramian_based(


def _compute_gramian_sum(jacobians: deque[Tensor]) -> PSDMatrix:
gramian = sum([compute_gramian(matrix) for matrix in jacobians])
dtype = reduce(torch.promote_types, {jacobian.dtype for jacobian in jacobians})
gramian = sum(compute_gramian(jacobian.to(dtype=dtype)) for jacobian in jacobians)
return cast(PSDMatrix, gramian)


Expand Down
17 changes: 17 additions & 0 deletions tests/unit/autogram/test_engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import pytest
import torch
from pytest import mark, param
from settings import DEVICE
from torch import Tensor
from torch.nn import BatchNorm2d, InstanceNorm2d, Linear, Module, Parameter
from torch.optim import SGD
Expand Down Expand Up @@ -436,6 +437,22 @@ def test_compute_gramian_manual() -> None:
assert_close(gramian, expected_gramian)


@mark.parametrize("batch_dim", [None, 0])
def test_compute_gramian_mixed_parameter_dtypes(batch_dim: int | None) -> None:
low = Linear(1, 1, bias=False, device=DEVICE, dtype=torch.float16)
high = Linear(1, 1, bias=False, device=DEVICE, dtype=torch.float64)
engine = Engine(low, high, batch_dim=batch_dim)
# The derivatives fit in float16, but their squared values overflow in that dtype.
inputs = ones_(2, 1, dtype=torch.float16) * 512
output = (low(inputs) + high(inputs.double())).flatten()
rows = [
torch.autograd.grad(value, (low.weight, high.weight), retain_graph=True) for value in output
]
jacobian = torch.stack([torch.cat(row).flatten() for row in rows])

assert_close(engine.compute_gramian(output), jacobian @ jacobian.T)
Comment thread
ValerianRey marked this conversation as resolved.
Resolved


@mark.parametrize(
"shape",
[
Expand Down
14 changes: 8 additions & 6 deletions tests/unit/autojac/test_jac_to_grad.py
Original file line number Diff line number Diff line change
Expand Up @@ -299,18 +299,20 @@ def test_mixed_dtypes(optimize: bool) -> None:
"""

aggregator = base_agg()
t1 = tensor_(1.0, dtype=torch.float32, requires_grad=True)
t1 = tensor_(1.0, dtype=torch.float16, requires_grad=True)
t2 = tensor_([2.0, 3.0], dtype=torch.float64, requires_grad=True)
jac = tensor_([[-4.0, 1.0, 1.0], [6.0, 1.0, 1.0]], dtype=torch.float64)
t1.__setattr__("jac", jac[:, 0].to(dtype=torch.float32))
# The low-precision block is finite, but squaring it in float16 overflows.
jac = tensor_([[-512.0, 1.0, 1.0], [512.0, 1.0, 1.0]], dtype=torch.float64)
t1.__setattr__("jac", jac[:, 0].to(dtype=torch.float16))
t2.__setattr__("jac", jac[:, 1:])
expected_grad = aggregator(jac)

jac_to_grad([t1, t2], aggregator, optimize_gramian_computation=optimize)
weights = jac_to_grad([t1, t2], aggregator, optimize_gramian_computation=optimize)

assert t1.grad is not None and t1.grad.dtype == torch.float32
assert_close(weights, aggregator.weighting(jac))
assert t1.grad is not None and t1.grad.dtype == torch.float16
assert t2.grad is not None and t2.grad.dtype == torch.float64
assert_grad_close(t1, expected_grad[0].to(dtype=torch.float32))
assert_grad_close(t1, expected_grad[0].to(dtype=torch.float16))
assert_grad_close(t2, expected_grad[1:])


Expand Down
Loading