Repository navigation
fix(autojac): Handle repeated tensors in jac_to_grad - #844
Merged
ValerianRey merged 1 commit intoNov 7, 2026
Merged
Conversation
SajalDevX
requested review from
a team,
PierreQuinton and
ValerianRey
as code owners
November 7, 2026 06:37
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.
If the same tensor appears more than once in the
tensorsgiven tojac_to_grad, it breaks:retain_jac=False, it crashes withAttributeError: 'Parameter' object has no attribute 'jac', because_free_jacsdeletes.jacon the first occurrence and then tries again. By that point some.jacfields are already gone and no.gradhas been filled.retain_jac=True, the repeated tensor's Jacobian is concatenated twice. Its gradient gets accumulated twice, and for non-linear aggregators like UPGrad the duplicated columns also change the Gramian, so every gradient comes out wrong.This happens easily when you merge parameter lists from modules that overlap, for example
list(model.parameters()) + list(model.encoder.parameters()).backwardandmtl_backwardalready handle repeatedinputs/shared_paramsby putting them in anOrderedSet. I did the same thing injac_to_grad, so each tensor is only used once, and I added a sentence about it to the docstring.Test: I added
test_repeated_tensorstotests/unit/autojac/test_jac_to_grad.py. It runs forretain_jacTrue/False andoptimize_gramian_computationTrue/False. Without the fix, all 4 cases fail (2 with theAttributeError, 2 with a wrong gradient). With the fix, all 4 pass.ruff,tyandpytest tests/unit -W error(CPU) also pass.