In the code sample, I print the difference: print((out - out_opt).abs().max()) and it gives 0 for me. So the stack does the same thing as the function you shared.
Is the function you shared doing what you want?