Repository navigation
fix(autojac): Support tensors of different dtypes in jac_to_grad - #821
Merged
ValerianRey merged 2 commits intoOct 8, 2026
Merged
Conversation
The Jacobians of all tensors are concatenated into a single matrix, so the aggregated gradient vector is in the promoted dtype, and assigning a slice of it to the .grad field of a tensor of lower precision raised a RuntimeError. With optimize_gramian_computation=True, the tensordot between the weights and a Jacobian of a different dtype failed too. Each gradient is now cast to the dtype of its tensor, as torch.autograd does.
SajalDevX
requested review from
a team,
PierreQuinton and
ValerianRey
as code owners
October 8, 2026 03:13
ValerianRey
approved these changes
Oct 8, 2026
ValerianRey
left a comment
Member
There was a problem hiding this comment.
Very good catch. This was a major bug IMO.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
jac_to_gradfails with aRuntimeErrorwhen the tensors do not all have the same dtype, for example a model with some parameters infloat32and others infloat64.torch.autograd.backwardandautojac.backwardboth handle this fine (each.jacfield is in the dtype of its tensor), butjac_to_gradcannot then turn these Jacobians into gradients:optimize_gramian_computation=False,_unite_jacobiansconcatenates the Jacobians into a single matrix, which promotes them to the highest dtype. The aggregated gradient vector is therefore in that dtype, and assigning a slice of it to the.gradfield of a tensor of lower precision is rejected by torch.optimize_gramian_computation=True, the weights are extracted from the sum of the Gramians (again in the promoted dtype), andtorch.tensordot(weights, jacobian, dims=1)fails for every Jacobian of a different dtype.Repro (CPU):
On
main:and with
jac_to_grad(model.parameters(), UPGrad(), optimize_gramian_computation=True):Solution
Cast each gradient to the dtype of its tensor, which is what
torch.autograddoes:_disunite_gradient, each reshaped slice of the gradient vector is cast with.to(dtype=t.dtype);_gramian_based, the weights are cast to the dtype of each Jacobian before thetensordot.When all tensors share the same dtype (the usual case),
.to(dtype=...)is a no-op and returns the same tensor, so nothing changes. With this change the repro prints[torch.float32, torch.float32, torch.float64, torch.float64]for the.gradfields in both modes, and the gradients obtained withMean()matchtorch.autograd.grad(losses.mean(), model.parameters()).Tests
test_mixed_dtypesintests/unit/autojac/test_jac_to_grad.py, parametrized overoptimize_gramian_computation. It gives afloat32tensor and afloat64tensor.jacfields of their own dtype, callsjac_to_gradand checks that each.gradhas the dtype of its tensor and the expected value. Both parametrizations fail onmain(with the two errors above) and pass with the fix. The dtypes are set explicitly, so the test checks the same thing underfloat32and underPYTEST_TORCH_DTYPE=float64.pytest tests/unit/autojac -W error: 396 passed, for bothfloat32andPYTEST_TORCH_DTYPE=float64(CPU only).pytest tests/unit/aggregation tests/unit/test_deprecations.py -W error: 1883 passed, 2 skipped.ruff check,ruff format --checkandty checkpass on the changed files.Added an entry under
[Unreleased] / Fixedin the changelog.