[Feature] Add TensorDict.backward() - #1733
Merged
Merged
Conversation
Add TensorDictBase.backward() mirroring torch.Tensor.backward() across differentiable tensor leaves: - Recursively collects leaves that require gradients; non-differentiable leaves are ignored, and an error is raised when none requires grad. - With gradient=None, uses an implicit gradient of 1 when every differentiable leaf is scalar (equivalent to sum(reduce=True).backward()), and raises the standard PyTorch-style error otherwise. - With an explicit gradient, requires a TensorDictBase whose entries match the differentiable leaves by nested key, with clear errors for missing keys and shape mismatches. Heterogeneous shapes, dtypes and devices are supported, enabling weighted losses via a matching TensorDict. - Forwards retain_graph, create_graph and inputs (accepting a TensorDictBase for the latter) to a single torch.autograd.backward() call. The method is exposed on tensorclasses through the TD fallback list. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
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.
Description
Adds
TensorDictBase.backward()with semantics matchingtorch.Tensor.backward()across differentiable tensor leaves.Behavior
torch.autograd.backward(tensors, grad_tensors, ...)call. Non-differentiable leaves are ignored; an error is raised when no leaf requires gradients.gradient=None, an implicit gradient of1is used when every differentiable leaf is scalar, soloss_td.backward()is equivalent toloss_td.sum(reduce=True).backward(). The standard PyTorch-style error is raised if any differentiable leaf is non-scalar.gradient, a matchingTensorDictBaseis required. Gradients are matched to leaves by nested key, with clear errors for missing keys and incompatible shapes. Heterogeneous leaf shapes, devices and dtypes are supported, which enables weighted losses:retain_graph,create_graphandinputsare forwarded consistently withtorch.Tensor.backward();inputsalso accepts aTensorDictBase.TensorDict.sum()semantics are unchanged: plain.sum()still reduces each leaf independently and returns a TensorDict, and.sum(reduce=True)remains the explicit full reduction..pyistub).Tests
TestBackwardintest/tensordict/test_methods.pycovers scalar and non-scalar leaves, nested keys, explicit gradient TensorDicts, weighted gradients (including parity with(loss_td * weights).sum(reduce=True).backward()), mixed differentiable/non-differentiable leaves, missing/incompatible/mis-typed gradients, no differentiable leaves,retain_graph/create_graph/inputsforwarding, and parity with the equivalent plain-PyTorch expressions. A parametrizedtest_backwardruns against all TensorDict variants (nested, stacked, permuted, h5, params, ...), plus a tensorclass test.Docs
Documented in the "Gradient computation" section of
docs/source/reference/td.rst; the docstring ships a runnable example.🤖 Generated with Claude Code