Solved by KFrank in post #3 
              
              
                Hi Ilya! 

First off, I suspect that you don’t* really want to do what you think 
you want to do. 
However, making some guesses about what (you think) you want, 
you could try something like this. 
The key issue is that argmin maps onto discrete integers, and so, 
is not usefully differentiable.  So…