I stuck at customizing autograd.Function for multiple output

An example would be very helpful. Thank you.

Hi,
You just need to add retain_graph=True during your first call to backward (otherwise the graph will be freed, to save memory, while in reality you need still need it for the second call).

So the last two lines should be:

dx.backward(gradient=torch.tensor([7.]), inputs=[input], retain_graph=True)
result.backward(gradient=torch.tensor([3.]), inputs=[input])

This should fix your exception.

This will have the effect of storing in input.grad the gradient of dx wrt input multiplied by 7 + the gradient of result wrt input multiplied by 3.

To make it more efficient, you can also compute that in a single torch.autograd.backward call:

torch.autograd.backward(tensors=[dx, result], grad_tensors=[torch.tensor([7.]), torch.tensor([3.])])

Also, you mentioned:

And dx.retail_grad() or result.retail_grad() don’t do anything.

retain_grad is a method you can call on individual tensors, that will ensure they store a gradient wrt themselves in their own .grad field despite not being leaves in the computation graph (see this). In reality, you rarely need to use this. This is very different from the retain_graph I’m talking about, which is a parameter of the backward and grad functions, telling autograd to not free the computation graph yet, and which you have to use when you make multiple calls to backward or grad.

I hope this helps!