Hi,
The problem I have with your question is about which definition of derivative your use.
You can only take derivatives wrt an argument of the function you consider. Not another function (if you have a functional that takes a function as argument, you can do it of course, but it’s not the case here).
If you want the derivative wrt the result of that function. As you mentioned in your question and want 5 as an answer, then that is what your first sample with .retain_grad() gives you.