Fix torch.autograd.backward inputs validation (#150975)

- Fixes #150883
- Fixes #70504

This is my first PR to pytorch, so please tell me if I'm forgetting anything.

Pull Request resolved: https://github.com/pytorch/pytorch/pull/150975
Approved by: https://github.com/soulitzer
This commit is contained in:
Valérian Rey
2025-04-17 02:11:10 +00:00
committed by PyTorch MergeBot
parent 6f9ffaa991
commit f5851efed9
2 changed files with 17 additions and 10 deletions

View File

@ -2507,6 +2507,12 @@ class TestAutograd(TestCase):
lambda: torch.autograd.backward(fn(), gradient, inputs=[]),
)
def test_backward_with_scalar_input(self):
x = torch.randn([], dtype=torch.double, requires_grad=True)
out = x**2
out.backward(inputs=x)
self.assertEqual(x.grad, 2 * x)
def test_backward_with_nonleaf_inputs(self):
x = torch.randn(2, 2, dtype=torch.double, requires_grad=True)
x_nonleaf = x * 1