diff --git a/CHANGELOG.md b/CHANGELOG.md index 9e476476..59379281 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/src/torchjd/autogram/_engine.py b/src/torchjd/autogram/_engine.py index 383ebd7b..8b8823e7 100644 --- a/src/torchjd/autogram/_engine.py +++ b/src/torchjd/autogram/_engine.py @@ -1,3 +1,4 @@ +from functools import reduce from typing import cast import torch @@ -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 diff --git a/src/torchjd/autogram/_gramian_accumulator.py b/src/torchjd/autogram/_gramian_accumulator.py index 432b73f0..b4ca3e1c 100644 --- a/src/torchjd/autogram/_gramian_accumulator.py +++ b/src/torchjd/autogram/_gramian_accumulator.py @@ -1,3 +1,5 @@ +from torch import dtype + from torchjd.linalg import PSDMatrix @@ -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: diff --git a/src/torchjd/autogram/_gramian_computer.py b/src/torchjd/autogram/_gramian_computer.py index 93801273..9d955c2b 100644 --- a/src/torchjd/autogram/_gramian_computer.py +++ b/src/torchjd/autogram/_gramian_computer.py @@ -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 @@ -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.""" @@ -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.""" @@ -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 diff --git a/src/torchjd/autogram/_module_hook_manager.py b/src/torchjd/autogram/_module_hook_manager.py index 1b52a3dd..8f326f30 100644 --- a/src/torchjd/autogram/_module_hook_manager.py +++ b/src/torchjd/autogram/_module_hook_manager.py @@ -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) diff --git a/src/torchjd/autojac/_jac_to_grad.py b/src/torchjd/autojac/_jac_to_grad.py index b5a10b13..09ad0d31 100644 --- a/src/torchjd/autojac/_jac_to_grad.py +++ b/src/torchjd/autojac/_jac_to_grad.py @@ -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 @@ -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) diff --git a/tests/unit/autogram/test_engine.py b/tests/unit/autogram/test_engine.py index 6cdde8cc..af8017b1 100644 --- a/tests/unit/autogram/test_engine.py +++ b/tests/unit/autogram/test_engine.py @@ -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 @@ -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) + + @mark.parametrize( "shape", [ diff --git a/tests/unit/autojac/test_jac_to_grad.py b/tests/unit/autojac/test_jac_to_grad.py index 4a1b376f..196004dc 100644 --- a/tests/unit/autojac/test_jac_to_grad.py +++ b/tests/unit/autojac/test_jac_to_grad.py @@ -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:])