Skip to content

Commit 1b3688a

Browse files
authored
fix(autojac): Support tensors of different dtypes in jac_to_grad (#821)
1 parent 68cd21b commit 1b3688a

3 files changed

Lines changed: 32 additions & 2 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,10 @@ changelog does not include internal changes that do not affect the user.
3434
- Fixed `Engine.compute_gramian` silently ignoring the contribution of a module when one of its
3535
forward passes had no associated backward pass (e.g. because its output was detached). It now
3636
raises a `ValueError` instead.
37+
- Fixed `jac_to_grad` failing with a `RuntimeError` when the tensors do not all have the same dtype
38+
(e.g. a model with some parameters in `float32` and others in `float64`). The aggregated gradient
39+
was computed in the promoted dtype and could not be assigned to the `.grad` field of the tensors
40+
of lower precision. Each tensor now gets a `.grad` of its own dtype, like with `torch.autograd`.
3741

3842
## [0.17.1] - 2026-09-23
3943

‎src/torchjd/autojac/_jac_to_grad.py‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -205,7 +205,7 @@ def _gramian_based(
205205
gradients = list[Tensor]()
206206
while jacobians:
207207
jacobian = jacobians.popleft() # get jacobian + dereference it to free memory asap
208-
gradients.append(torch.tensordot(weights, jacobian, dims=1))
208+
gradients.append(torch.tensordot(weights.to(dtype=jacobian.dtype), jacobian, dims=1))
209209

210210
return gradients, weights
211211

@@ -229,7 +229,9 @@ def _disunite_gradient(
229229
tensors: list[TensorWithJac],
230230
) -> list[Tensor]:
231231
gradient_vectors = gradient_vector.split([t.numel() for t in tensors])
232-
gradients = [g.reshape(t.shape) for g, t in zip(gradient_vectors, tensors, strict=True)]
232+
gradients = [
233+
g.reshape(t.shape).to(dtype=t.dtype) for g, t in zip(gradient_vectors, tensors, strict=True)
234+
]
233235
return gradients
234236

235237

‎tests/unit/autojac/test_jac_to_grad.py‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from typing import Any
22

3+
import torch
34
from pytest import mark, raises
45
from torch import Tensor
56
from torch.testing import assert_close
@@ -266,6 +267,29 @@ def test_noncontiguous_jac() -> None:
266267
assert_grad_close(t, g)
267268

268269

270+
@mark.parametrize("optimize", [True, False])
271+
def test_mixed_dtypes(optimize: bool) -> None:
272+
"""
273+
Tests that jac_to_grad works when the tensors do not all have the same dtype. Each tensor should
274+
get a .grad of its own dtype, as torch's backward would do.
275+
"""
276+
277+
aggregator = base_agg()
278+
t1 = tensor_(1.0, dtype=torch.float32, requires_grad=True)
279+
t2 = tensor_([2.0, 3.0], dtype=torch.float64, requires_grad=True)
280+
jac = tensor_([[-4.0, 1.0, 1.0], [6.0, 1.0, 1.0]], dtype=torch.float64)
281+
t1.__setattr__("jac", jac[:, 0].to(dtype=torch.float32))
282+
t2.__setattr__("jac", jac[:, 1:])
283+
expected_grad = aggregator(jac)
284+
285+
jac_to_grad([t1, t2], aggregator, optimize_gramian_computation=optimize)
286+
287+
assert t1.grad is not None and t1.grad.dtype == torch.float32
288+
assert t2.grad is not None and t2.grad.dtype == torch.float64
289+
assert_grad_close(t1, expected_grad[0].to(dtype=torch.float32))
290+
assert_grad_close(t2, expected_grad[1:])
291+
292+
269293
@mark.parametrize("aggregator", [base_agg(), ConFIG()])
270294
def test_aggregator_hook_is_run(aggregator: Aggregator) -> None:
271295
"""

0 commit comments

Comments
 (0)