I fond this code may be interesting as it shows how grad() function may be used to compute sum of gradients “between two tensors”.
x = torch.tensor(1., requires_grad=True)
w = torch.tensor(2., requires_grad=True)
b = torch.tensor(3., requires_grad=True)

y = w * x + b    # y = 2 * x + 3

gd = torch.autograd.grad(outputs=y, inputs=x)
print(gd) #(tensor(2.),)
gd = torch.autograd.grad(outputs=y, inputs=b)
print(gd) #(tensor(1.),)