Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixing Tensor.backward's function signature #1376

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

JamesG9802
Copy link

@JamesG9802 JamesG9802 commented Sep 21, 2024

Fixes #692

TLDR: Tensor.backward has a different parameter order compared to PyTorch and also swaps retain_graph and create_graph in its internal function call.

See https://pytorch.org/docs/stable/generated/torch.Tensor.backward.html for backward's function signature:
Tensor.backward(gradient=None, retain_graph=None, create_graph=False, inputs=None)

The current TorchSharp version's function signature is:
Tensor.backward(grad_tensors=null, create_graph=false, retain_graph=false, inputs=null)

Note the difference between the ordering of retain_graph and create_graph. Tensor.backward is just a wrapper to torch.autograd.backward which has a function signature of:
autograd.backward(tensors, grad_tensors=null, retain_graph=null, create_graph=false, inputs=null)

This means calling Tensor.backward(retain_graph: true) in TorchSharp is actually Tensor.backward(create_graph:true) in PyTorch. Same thing for Tensor.backward(create_graph: true) actually being Tensor.backward(retain_graph:true).

The proposed fix is breaking and would change the Tensor.backward function signature to match PyTorch. However, nobody noticed for like 2 years anyway and imo retain_graph should actually mean retain_graph (and same for create_graph) 🙂.

Fixing reversed graph parameters.
@yueyinqiu yueyinqiu mentioned this pull request Sep 27, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant