From 840778c3d99a6596111338aa1090f22c531a283d Mon Sep 17 00:00:00 2001 From: AryanRG Date: Thu, 19 Nov 2026 03:58:31 +0530 Subject: [PATCH] Promote mixed-dtype Jacobians before computing their Gramian --- CHANGELOG.md | 2 ++ src/torchjd/autogram/_engine.py | 11 +++++++++++ src/torchjd/autogram/_gramian_accumulator.py | 4 ++++ src/torchjd/autogram/_gramian_computer.py | 6 ++++-- src/torchjd/autogram/_module_hook_manager.py | 1 + tests/unit/autogram/test_engine.py | 17 +++++++++++++++++ 6 files changed, 39 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 440d066d5..ed5ee5ef4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,8 @@ changelog does not include internal changes that do not affect the user. ### Fixed +- Fixed `autogram.Engine.compute_gramian` overflowing or losing precision when the modules have + trainable parameters of different dtypes. Partial Gramians are computed in the promoted dtype. - Fixed `.to()` not moving the tensors given to the `Constant`, `STCH`, `PBI` and `COSMOS` scalarizers (`weights` and `reference`). These tensors are now registered as non-persistent buffers, so they follow the dtype and device of the scalarizer without being added to its diff --git a/src/torchjd/autogram/_engine.py b/src/torchjd/autogram/_engine.py index 383ebd7b8..8b8823e75 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 432b73f0d..b4ca3e1ce 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 938012738..9d955c2b1 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 1b52a3dd1..8f326f308 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/tests/unit/autogram/test_engine.py b/tests/unit/autogram/test_engine.py index 6cdde8cc7..0fbd8e77a 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.float32) + high = Linear(1, 1, bias=False, device=DEVICE, dtype=torch.float64) + engine = Engine(low, high, batch_dim=batch_dim) + # The individual derivatives fit in float32, but their Gramian needs float64. + inputs = ones_(2, 1, dtype=torch.float32) * (2.0**65) + 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", [